Skip to content

Commit

Permalink
Merge pull request #73 from leifniem/master
Browse files Browse the repository at this point in the history
Add option to provide middleware file
  • Loading branch information
omar-dulaimi authored Mar 6, 2023
2 parents 25f207c + 1830937 commit 8970d5a
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 28 deletions.
18 changes: 9 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@

- [About The Project](#about-the-project)
- [Supported Prisma Versions](#supported-prisma-versions)
- [Prisma 4](#prisma-4)
- [Prisma 2/3](#prisma-23)
- [Prisma 4](#prisma-4)
- [Prisma 2/3](#prisma-23)
- [Supported tRPC Versions](#supported-trpc-versions)
- [tRPC 10](#trpc-10)
- [tRPC 9](#trpc-9)
- [tRPC 10](#trpc-10)
- [tRPC 9](#trpc-9)
- [Installation](#installation)
- [Usage](#usage)
- [Customizations](#customizations)
Expand Down Expand Up @@ -174,9 +174,10 @@ model User {

| Option | Description | Type | Default |
| -------------------------- | -------------------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `output` | Output directory for the generated routers and zod schemas | `string` | `./generated`
| `withZod` | Use Zod for input validation | `boolean` | `true` |
| `withMiddleware` | Attaches a global middleware that runs before all procedures | `boolean` | `true` |
| `output` | Output directory for the generated routers and zod schemas | `string` | `./generated` |
| `withMiddleware` | Attaches a global middleware that runs before all procedures | `boolean or string`| `true` |
| `output` | Output directory for the generated routers and zod schemas | `string` | `./generated` |
| `withZod` | Use Zod for input validation | `boolean` | `true` |
| `withShield` | Generates a tRPC Shield to use as a permissions layer | `boolean` | `true` |
| `contextPath` | Sets the context path used in your routers | `string` | `../../../../src/context` |
| `trpcOptionsPath` | Sets the tRPC instance options | `string` | `../../../../src/trpcOptions` |
Expand All @@ -185,15 +186,14 @@ model User {
| `showModelNameInProcedure` | When disabled, the generated procedure no longer includes the name of the Prisma model | `boolean` | `true` |
| `generateModelActions` | Enables the generation of specific model actions | `string` | `aggregate,aggregateRaw,count,create,createMany,delete,deleteMany,findFirst,findFirstOrThrow,findMany,findRaw,findUnique,findUniqueOrThrow,groupBy,update,updateMany,upsert` |


Use additional options in the `schema.prisma`

```prisma
generator trpc {
provider = "prisma-trpc-generator"
output = "./trpc"
withMiddleware = "../middleware"
withZod = false
withMiddleware = false
withShield = false
contextPath = "../context"
trpcOptionsPath = "../trpcOptions"
Expand Down
4 changes: 4 additions & 0 deletions prisma/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default async ({ ctx, next }) => {
console.log("Hello from the imported Middleware");
return next({ ctx });
}
2 changes: 1 addition & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ generator trpc {
provider = "node ./lib/generator.js"
isGenerateSelect = true
isGenerateInclude = true
withMiddleware = true
withMiddleware = "./middleware"
withShield = true
contextPath = "./context"
trpcOptionsPath = "./trpcOptions"
Expand Down
4 changes: 3 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ const configBoolean = z
.enum(['true', 'false'])
.transform((arg) => JSON.parse(arg));

const configStringOrBoolean = z.union([configBoolean, z.string().default("../../../../src/middleware")])

const modelActionEnum = z.nativeEnum(DMMF.ModelAction);

export const configSchema = z.object({
withMiddleware: configBoolean.default('true'),
withMiddleware: configStringOrBoolean.default('true'),
withShield: configBoolean.default('true'),
withZod: configBoolean.default('true'),
contextPath: z.string().default('../../../../src/context'),
Expand Down
61 changes: 44 additions & 17 deletions src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ const getProcedureName = (config: Config) => {
return config.withShield
? 'shieldedProcedure'
: config.withMiddleware
? 'protectedProcedure'
: 'publicProcedure';
? 'protectedProcedure'
: 'publicProcedure';
};

export const generateCreateRouterImport = ({
Expand Down Expand Up @@ -50,6 +50,17 @@ export const generateShieldImport = (
});
};

export const generateMiddlewareImport = (
sourceFile: SourceFile,
options: GeneratorOptions,
) => {
const outputDir = parseEnvValue(options.generator.output as EnvValue);
sourceFile.addImportDeclaration({
moduleSpecifier: getRelativePath(outputDir, 'middleware'),
namedImports: ['permissions'],
});
};

export const generateRouterImport = (
sourceFile: SourceFile,
modelNamePlural: string,
Expand Down Expand Up @@ -88,14 +99,13 @@ export function generateBaseRouter(
}

sourceFile.addStatements(/* ts */ `
export const t = trpc.initTRPC.context<Context>().create(${
config.trpcOptionsPath ? 'trpcOptions' : ''
});
export const t = trpc.initTRPC.context<Context>().create(${config.trpcOptionsPath ? 'trpcOptions' : ''
});
`);

const middlewares = [];

if (config.withMiddleware) {
if (config.withMiddleware && typeof config.withMiddleware === "boolean") {
sourceFile.addStatements(/* ts */ `
export const globalMiddleware = t.middleware(async ({ ctx, next }) => {
console.log('inside middleware!')
Expand All @@ -107,36 +117,53 @@ export function generateBaseRouter(
});
}

if (config.withMiddleware && typeof config.withMiddleware === "string") {
sourceFile.addStatements(/* ts */ `
import defaultMiddleware from '${getRelativePath(
outputDir,
config.withMiddleware,
true,
options.schemaPath,
)}';
`);
sourceFile.addStatements(/* ts */ `
export const globalMiddleware = t.middleware(defaultMiddleware);`
);
middlewares.push({
type: 'global',
value: /* ts */ `.use(globalMiddleware)`,
});
}

if (config.withShield) {
sourceFile.addStatements(/* ts */ `
export const permissionsMiddleware = t.middleware(permissions);`);
export const permissionsMiddleware = t.middleware(permissions); `);
middlewares.push({
type: 'shield',
value: /* ts */ `
.use(permissions)`,
.use(permissions)`,
});
}

sourceFile.addStatements(/* ts */ `
export const publicProcedure = t.procedure;`);
export const publicProcedure = t.procedure; `);

if (middlewares.length > 0) {
const procName = getProcedureName(config);

middlewares.forEach((middleware, i) => {
if (i === 0) {
sourceFile.addStatements(/* ts */ `
export const ${procName} = t.procedure
`);
export const ${procName} = t.procedure
`);
}

sourceFile.addStatements(/* ts */ `
.use(${
middleware.type === 'shield'
? 'permissionsMiddleware'
: 'globalMiddleware'
.use(${middleware.type === 'shield'
? 'permissionsMiddleware'
: 'globalMiddleware'
})
`);
`);
});
}
}
Expand Down Expand Up @@ -193,7 +220,7 @@ export const getRouterSchemaImportByOpName = (
const inputType = getInputTypeByOpName(opType, modelName);

return inputType
? `import { ${inputType} } from "../schemas/${opType}${modelName}.schema";`
? `import { ${inputType} } from "../schemas/${opType}${modelName}.schema"; `
: '';
};

Expand Down

0 comments on commit 8970d5a

Please sign in to comment.