npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pothos-prisma-generator

v1.0.2

Published

## Overview

Downloads

618

Readme

pothos-prisma-generator

Overview

Automatic generation of GraphQL schema from prisma schema.

Generate a GraphQL schema from prisma.schema that can be queried as follows.

prisma.schema -> queries.graphql

  • count
  • findUnique
  • findFirst
  • findMany
  • createOne
  • createMany
  • updateOne
  • updateMany
  • deleteOne
  • deleteMany

The schema is generated internally at runtime, so no text output of the code is performed.

Sample code

Builder Settings

Add PrismaPlugin,PrismaUtil,PothosPrismaGeneratorPlugin
ScopeAuthPlugin must also be added when using the authorization function.

By setting replace and authority in pothosPrismaGenerator, you can refer to user information to separate the data to be inserted and the conditions to be applied.

The following settings are made by default. To disable, use autoScalers: false.

builder.addScalarType("BigInt" as never, BigIntResolver, {});
builder.addScalarType("Bytes" as never, ByteResolver, {});
builder.addScalarType("DateTime" as never, DateTimeResolver, {});
builder.addScalarType("Json" as never, JSONResolver, {});
builder.addScalarType("Decimal" as never, HexadecimalResolver, {});
  • Here is an example of Builder settings
import SchemaBuilder from "@pothos/core";
import PrismaPlugin from "@pothos/plugin-prisma";
import PrismaTypes from "./generated/pothos-types";
import { Context, prisma } from "./context";
import { Prisma } from "@prisma/client";
import { DateTimeResolver } from "graphql-scalars";
import PrismaUtils from "@pothos/plugin-prisma-utils";
import ScopeAuthPlugin from "@pothos/plugin-scope-auth";
import PothosPrismaGeneratorPlugin from "pothos-prisma-generator";

/**
 * Create a new schema builder instance
 */
export const builder = new SchemaBuilder<{
  Context: Context;
  // PrismaTypes: PrismaTypes; //Not used because it is generated automatically
}>({
  plugins: [
    PrismaPlugin,
    PrismaUtils,
    ScopeAuthPlugin,
    PothosPrismaGeneratorPlugin,
  ],
  prisma: {
    client: prisma,
    dmmf: Prisma.dmmf,
  },
  // if necessary
  authScopes: async (context) => ({
    authenticated: !!context.user,
  }),
  pothosPrismaGenerator: {
    // Disable `autoScalers
    //autoScalers: false,

    // Replace the following directives
    // /// @pothos-generator input {data:{author:{connect:{id:"%%USER%%"}}}}
    replace: { "%%USER%%": ({ context }) => context.user?.id },

    // Set the following permissions
    /// @pothos-generator any {authority:["ROLE"]}
    authority: ({ context }) => context.user?.roles ?? [],
  },
});

How to Write Directives

/// @pothos-generator [Directive name] [Json5 format parameters]
model ModelName {
  …
}

Operation name

If no operation is specified on the directive, it is applied to all.

  • query
    findUnique, findFirst, findMany, count
  • find
    findUnique, findFirst,findMany
  • create
    createOne, createMany
  • update
    updateOne, updateMany
  • delete
    deleteOne, deleteMany
  • mutation
    createOne, createMany, updateOne, updateMany, deleteOne, deleteMany

Select the operation to output

operation {include:[...OperationNames],exclude[...OperationNames]}

The default is all output.

  • Example1
    Include createOne and `updateOne
/// @pothos-generator operation {include:["createOne","updateOne"]}
  • Example2
    Exclude deleteOne and `deleteMany
/// @pothos-generator operation {exclude:["delete"]}

Model directive

Sets options to be set for Pothos fields.

  • Operator option
{
  include:[...OperationNames],
  exclude:[...OperationNames],
  option:{OptionName:Params,…}
}
  • Example
    Set auth-plugin's authScopes for createOne,createMany,updateOne,updateMany,deleteOne,deleteMany.
/// @pothos-generator option {include:["mutation"],option:{authScopes:{authenticated:true}}}

Set the fields that are allowed to be entered

  • Operator input-field
{
  include:[...OperationNames],
  exclude:[...OperationNames],
  fields:{include:[...FieldNames],exclude:[...FieldNames]}
}
  • Example
    create allows email and name to be entered.
/// @pothos-generator input-field {include:["create"],fields:{include:["email","name"]}}

Set the data to be interrupted in prisma data

  • Operator input-data
{
  include:[...OperationNames],
  exclude:[...OperationNames],
  data:InputData,
  authority:[...Authorities]
}

When authority is set, the first matching input-data directive is used.
The replace option of builder will replace the content.

  • Example
    Replace authorId with %%USER%% when inserting data
/// @pothos-generator input-data {data:{authorId:"%%USER%%"}}

Interrupts where to pass to prisma; if authority is set, the first match is used

  • Operator where
{
  include:[...OperationNames],
  exclude:[...OperationNames],
  where:Where,
  authority:[...Authorities]}

The replace option of builder will replace the content.

  • Example
    No condition if you have USER permission, otherwise published:true will be added to the condition.
/// @pothos-generator where {include:["query"],where:{},authority:["USER"]}
/// @pothos-generator where {include:["query"],where:{published:true}}

Interrupts orderBy to pass to prisma; if authority is set, the first match is used

  • Operator order
{
  include:[...OperationNames],
  exclude:[...OperationNames],
  orderBy:order,
  authority:[...Authorities]
}
  • Example
    Defaults to order in ascending order of title.
/// @pothos-generator order {orderBy:{title:"asc"}}

Authority to execute operations

  • Operator executable
{
  include:[...OperationNames],
  exclude:[...OperationNames],
  authority:[...Authorities]
}
  • Example
    You can perform mutation only if you retain USER privileges.
/// @pothos-generator executable {include:["mutation"],authority:["USER"]}

limit on the number of events

  • Operator limit
{
  include:[...OperationNames],
  exclude:[...OperationNames],
  limit:LIMIT,
  authority:[...Authorities]
}
  • Example
    Set the maximum number of acquisitions to 10
/// @pothos-generator limit {limit:10}

Field directive

Field read permission

  • Operator readable
[...Authorities];

If Authorities is empty, it will be removed from the GraphQL Object and will not appear in the Query.

  • Example1
    It can only be retrieved if you have ADMIN permission. Otherwise, adding it to the query will raise an exception.
 /// @pothos-generator readable ["ADMIN"]
  • Example2
    No one has read permission, so the field is invisible.
/// @pothos-generator readable []

Prisma schema settings

The output content is controlled by @pothos-generator.
Details are omitted since the specification is still under development and is likely to change.

The authScopes are written for the option sample, but need not be introduced if executable/readable is used.

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

/// @pothos-generator operation {include:["createOne","updateOne","findMany"]}
/// @pothos-generator option {include:["mutation"],option:{authScopes:{ADMIN:true}}}
/// @pothos-generator input-field {include:["create"],fields:{include:["email","name"]}}
/// @pothos-generator input-field {include:["update"],fields:{include:["name"]}}
model User {
  id        String   @id @default(uuid())
  /// @pothos-generator readable ["ADMIN"]
  email     String   @unique
  name      String   @default("User")
  posts     Post[]
  /// @pothos-generator readable ["ADMIN"]
  roles     Role[]   @default([USER])
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

/// @pothos-generator operation {exclude:["deleteMany"]}
/// @pothos-generator executable {include:["mutation"],authority:["USER"]}
/// @pothos-generator input-field {fields:{exclude:["id","createdAt","updatedAt","author"]}}
/// @pothos-generator input-data {data:{authorId:"%%USER%%"}}
/// @pothos-generator where {include:["query"],where:{},authority:["USER"]}
/// @pothos-generator where {include:["query"],where:{published:true}}
/// @pothos-generator where {include:["update","delete"],where:{authorId:"%%USER%%"}}
/// @pothos-generator order {orderBy:{title:"asc"}}
model Post {
  id          String     @id @default(uuid())
  published   Boolean    @default(false)
  title       String     @default("New Post")
  content     String     @default("")
  author      User?      @relation(fields: [authorId], references: [id])
  authorId    String?
  categories  Category[]
  /// @pothos-generator readable []
  createdAt   DateTime   @default(now())
  updatedAt   DateTime   @updatedAt
  publishedAt DateTime   @default(now())
}

/// @pothos-generator order {orderBy:{name:"asc"}}
/// @pothos-generator input-field {fields:{exclude:["id","createdAt","updatedAt","posts"]}}
model Category {
  id        String   @id @default(uuid())
  name      String
  posts     Post[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

enum Role {
  ADMIN
  USER
}

Substitution of Input Data

If a replacement string is set for builder, it will replace the strings in the input-data and where directives when the query is executed.
This can be used, for example, to write logged-in user information.

// Replace the following directives
// /// @pothos-generator input {data:{author:{connect:{id:"%%USER%%"}}}}
replace: { "%%USER%%": async ({ context }) => context.user?.id },

Switching query conditions by permissions

You can switch where by setting permissions.
In the following case, the condition where:{} is added if you are logged in, and ,where:{published:true} if you are not logged in.

// Set the following permissions
// /// @pothos-generator any {authority:["ROLE"]}

// Sample assumes ["ADMIN", "USER"] is set during authentication
authority: ({ context }) => context.user?.roles ?? [],