zod-prisma
Advanced tools
Comparing version 0.3.0 to 0.3.1
@@ -9,2 +9,3 @@ 'use strict'; | ||
var typescript = require('typescript'); | ||
var z = _interopDefault(require('zod')); | ||
@@ -113,2 +114,9 @@ var getJSDocs = function getJSDocs(docString) { | ||
var configSchema = /*#__PURE__*/z.object({ | ||
relationModel: /*#__PURE__*/z["enum"](['default', 'true', 'false'])["default"]('true').transform(function (val) { | ||
return val === 'default' ? val : Boolean(val); | ||
}), | ||
modelSuffix: /*#__PURE__*/z.string()["default"]('Model'), | ||
modelCase: /*#__PURE__*/z["enum"](['PascalCase', 'camelCase'])["default"]('PascalCase') | ||
}); | ||
generatorHelper.generatorHandler({ | ||
@@ -131,8 +139,8 @@ onManifest: function onManifest() { | ||
}); | ||
var _options$generator$co = options.generator.config, | ||
relationModel = _options$generator$co.relationModel, | ||
_options$generator$co2 = _options$generator$co.modelSuffix, | ||
modelSuffix = _options$generator$co2 === void 0 ? 'Model' : _options$generator$co2, | ||
_options$generator$co3 = _options$generator$co.modelCase, | ||
modelCase = _options$generator$co3 === void 0 ? 'PascalCase' : _options$generator$co3; | ||
var parsedConfig = configSchema.safeParse(options.generator.config); | ||
if (!parsedConfig.success) throw new Error('Incorrect config provided. Please check the values you provided and try again.'); | ||
var _parsedConfig$data = parsedConfig.data, | ||
relationModel = _parsedConfig$data.relationModel, | ||
modelSuffix = _parsedConfig$data.modelSuffix, | ||
modelCase = _parsedConfig$data.modelCase; | ||
@@ -155,3 +163,3 @@ var formatModelName = function formatModelName(name, prefix) { | ||
models.forEach(function (model) { | ||
var _prismaClient$output; | ||
var _prismaClient$output, _relativePath; | ||
@@ -182,5 +190,7 @@ indexSource.addExportDeclaration({ | ||
}); | ||
var relativePath = prismaClient != null && (_prismaClient$output = prismaClient.output) != null && _prismaClient$output.value ? path.relative(outputPath, prismaClient.output.value) : null; | ||
if (relativePath && !(relativePath.startsWith('./') || relativePath.startsWith('../'))) relativePath = "./" + relativePath; | ||
sourceFile.addImportDeclaration({ | ||
kind: tsMorph.StructureKind.ImportDeclaration, | ||
moduleSpecifier: prismaClient != null && (_prismaClient$output = prismaClient.output) != null && _prismaClient$output.value ? path.relative(outputPath, prismaClient.output.value) : '@prisma/client', | ||
moduleSpecifier: (_relativePath = relativePath) != null ? _relativePath : '@prisma/client', | ||
namedImports: [model.name].concat(enumFields.map(function (f) { | ||
@@ -187,0 +197,0 @@ return f.type; |
@@ -1,2 +0,2 @@ | ||
"use strict";var e,t=(e=require("path"))&&"object"==typeof e&&"default"in e?e.default:e,n=require("@prisma/generator-helper"),r=require("ts-morph"),i=require("typescript"),a=function(e){var t=[];if(e){var n=e.split("\n").filter((function(e){return!e.trimLeft().startsWith("@zod")}));n.length&&(t.push("/**"),n.forEach((function(e){return t.push(" * "+e)})),t.push(" */"))}return t},o=function(e,t){void 0===t&&(t=function(e){return e.toString()});var n="z.unknown()",r=[""];if("scalar"===e.kind)switch(e.type){case"String":n="z.string()";break;case"Int":n="z.number()",r.push("int()");break;case"BigInt":n="z.bigint()";break;case"DateTime":n="z.date()";break;case"Float":case"Decimal":n="z.number()";break;case"Json":n="z.any()";break;case"Boolean":n="z.boolean()";break;case"Bytes":n="z.unknown()"}else"enum"===e.kind?n="z.nativeEnum("+e.type+")":"object"===e.kind&&(n=t(e.type));return e.isRequired||r.push("nullable()"),e.isList&&r.push("array()"),e.documentation&&r.push.apply(r,e.documentation.split("\n").filter((function(e){return e.trimLeft().startsWith("@zod")})).map((function(e){return e.trim().split("@zod.").slice(-1)[0]}))),""+n+r.join(".")},u=function(e,t,n){return void 0===n&&(n=!0),t.forEach((function(t){return e.write(t).conditionalNewLine(n)}))};n.generatorHandler({onManifest:function(){return{prettyName:"Zod Schemas",defaultOutput:"zod",version:"0.2.1"}},onGenerate:function(e){var n=new r.Project({skipAddingFilesFromTsConfig:!0}),c=e.generator.output.value,l=e.dmmf.datamodel.models,d=e.otherGenerators.find((function(e){return"prisma-client-js"===e.provider.value})),s=e.generator.config,m=s.relationModel,f=s.modelSuffix,p=void 0===f?"Model":f,h=s.modelCase,v=void 0===h?"PascalCase":h,w=function(e,t){return void 0===t&&(t=""),"camelCase"===v&&(e=e.slice(0,1).toLowerCase()+e.slice(1)),""+t+e+p},z=n.createSourceFile(c+"/index.ts",{},{overwrite:!0});return l.forEach((function(e){var l;z.addExportDeclaration({moduleSpecifier:"./"+e.name.toLowerCase()});var s=function(e){return w(e,"default"===m?"_":"")},f=function(e){return w("default"===m?e.toString():"Related"+e.toString())},p=n.createSourceFile(c+"/"+e.name.toLowerCase()+".ts",{statements:[{kind:r.StructureKind.ImportDeclaration,namespaceImport:"z",moduleSpecifier:"zod"}]},{overwrite:!0}),h=e.fields.filter((function(e){return"enum"===e.kind}));p.addImportDeclaration({kind:r.StructureKind.ImportDeclaration,moduleSpecifier:null!=d&&null!=(l=d.output)&&l.value?t.relative(c,d.output.value):"@prisma/client",namedImports:[e.name].concat(h.map((function(e){return e.type})))}),p.addStatements((function(t){return u(t,a(e.documentation))})),p.addVariableStatement({declarationKind:r.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:s(e.name),initializer:function(t){t.write("z.object(").inlineBlock((function(){e.fields.filter((function(e){return"object"!==e.kind})).forEach((function(e){u(t,a(e.documentation)),t.write(e.name+": "+o(e)).write(",").newLine()}))})).write(")")}}]});var v=e.fields.filter((function(e){return"object"===e.kind}));if(!1!==m&&v.length>0){var S=v.filter((function(t){return t.type!==e.name}));S.length>0&&p.addImportDeclaration({kind:r.StructureKind.ImportDeclaration,moduleSpecifier:"./index",namedImports:Array.from(new Set(S.flatMap((function(e){return["Complete"+e.type,f(e.type)]}))))}),p.addInterface({name:"Complete"+e.name,isExported:!0,extends:function(t){return t.write(e.name)},properties:v.map((function(e){return{name:e.name,type:"Complete"+e.type+(e.isList?"[]":"")+(e.isRequired?"":" | null")}}))}),p.addStatements((function(t){return u(t,["","/**"," * "+f(e.name)+" contains all relations on your model in addition to the scalars"," *"," * NOTE: Lazy required in case of potential circular dependencies within schema"," */"])})),p.addVariableStatement({declarationKind:r.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:f(e.name),type:"z.ZodSchema<Complete"+e.name+">",initializer:function(t){t.write("z.lazy(() => "+s(e.name)+".extend(").inlineBlock((function(){v.forEach((function(e){u(t,a(e.documentation)),t.write(e.name+": "+o(e,f)).write(",").newLine()}))})).write("))")}}]})}p.formatText({indentSize:2,convertTabsToSpaces:!0,semicolons:i.SemicolonPreference.Remove})})),n.save()}}); | ||
"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("path")),n=require("@prisma/generator-helper"),r=require("ts-morph"),i=require("typescript"),a=e(require("zod")),o=function(e){var t=[];if(e){var n=e.split("\n").filter((function(e){return!e.trimLeft().startsWith("@zod")}));n.length&&(t.push("/**"),n.forEach((function(e){return t.push(" * "+e)})),t.push(" */"))}return t},u=function(e,t){void 0===t&&(t=function(e){return e.toString()});var n="z.unknown()",r=[""];if("scalar"===e.kind)switch(e.type){case"String":n="z.string()";break;case"Int":n="z.number()",r.push("int()");break;case"BigInt":n="z.bigint()";break;case"DateTime":n="z.date()";break;case"Float":case"Decimal":n="z.number()";break;case"Json":n="z.any()";break;case"Boolean":n="z.boolean()";break;case"Bytes":n="z.unknown()"}else"enum"===e.kind?n="z.nativeEnum("+e.type+")":"object"===e.kind&&(n=t(e.type));return e.isRequired||r.push("nullable()"),e.isList&&r.push("array()"),e.documentation&&r.push.apply(r,e.documentation.split("\n").filter((function(e){return e.trimLeft().startsWith("@zod")})).map((function(e){return e.trim().split("@zod.").slice(-1)[0]}))),""+n+r.join(".")},c=function(e,t,n){return void 0===n&&(n=!0),t.forEach((function(t){return e.write(t).conditionalNewLine(n)}))},l=a.object({relationModel:a.enum(["default","true","false"]).default("true").transform((function(e){return"default"===e?e:Boolean(e)})),modelSuffix:a.string().default("Model"),modelCase:a.enum(["PascalCase","camelCase"]).default("PascalCase")});n.generatorHandler({onManifest:function(){return{prettyName:"Zod Schemas",defaultOutput:"zod",version:"0.2.1"}},onGenerate:function(e){var n=new r.Project({skipAddingFilesFromTsConfig:!0}),a=e.generator.output.value,d=e.dmmf.datamodel.models,s=e.otherGenerators.find((function(e){return"prisma-client-js"===e.provider.value})),f=l.safeParse(e.generator.config);if(!f.success)throw new Error("Incorrect config provided. Please check the values you provided and try again.");var m=f.data,p=m.relationModel,h=m.modelSuffix,v=m.modelCase,w=function(e,t){return void 0===t&&(t=""),"camelCase"===v&&(e=e.slice(0,1).toLowerCase()+e.slice(1)),""+t+e+h},z=n.createSourceFile(a+"/index.ts",{},{overwrite:!0});return d.forEach((function(e){var l,d;z.addExportDeclaration({moduleSpecifier:"./"+e.name.toLowerCase()});var f=function(e){return w(e,"default"===p?"_":"")},m=function(e){return w("default"===p?e.toString():"Related"+e.toString())},h=n.createSourceFile(a+"/"+e.name.toLowerCase()+".ts",{statements:[{kind:r.StructureKind.ImportDeclaration,namespaceImport:"z",moduleSpecifier:"zod"}]},{overwrite:!0}),v=e.fields.filter((function(e){return"enum"===e.kind})),S=null!=s&&null!=(l=s.output)&&l.value?t.relative(a,s.output.value):null;!S||S.startsWith("./")||S.startsWith("../")||(S="./"+S),h.addImportDeclaration({kind:r.StructureKind.ImportDeclaration,moduleSpecifier:null!=(d=S)?d:"@prisma/client",namedImports:[e.name].concat(v.map((function(e){return e.type})))}),h.addStatements((function(t){return c(t,o(e.documentation))})),h.addVariableStatement({declarationKind:r.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:f(e.name),initializer:function(t){t.write("z.object(").inlineBlock((function(){e.fields.filter((function(e){return"object"!==e.kind})).forEach((function(e){c(t,o(e.documentation)),t.write(e.name+": "+u(e)).write(",").newLine()}))})).write(")")}}]});var b=e.fields.filter((function(e){return"object"===e.kind}));if(!1!==p&&b.length>0){var y=b.filter((function(t){return t.type!==e.name}));y.length>0&&h.addImportDeclaration({kind:r.StructureKind.ImportDeclaration,moduleSpecifier:"./index",namedImports:Array.from(new Set(y.flatMap((function(e){return["Complete"+e.type,m(e.type)]}))))}),h.addInterface({name:"Complete"+e.name,isExported:!0,extends:function(t){return t.write(e.name)},properties:b.map((function(e){return{name:e.name,type:"Complete"+e.type+(e.isList?"[]":"")+(e.isRequired?"":" | null")}}))}),h.addStatements((function(t){return c(t,["","/**"," * "+m(e.name)+" contains all relations on your model in addition to the scalars"," *"," * NOTE: Lazy required in case of potential circular dependencies within schema"," */"])})),h.addVariableStatement({declarationKind:r.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:m(e.name),type:"z.ZodSchema<Complete"+e.name+">",initializer:function(t){t.write("z.lazy(() => "+f(e.name)+".extend(").inlineBlock((function(){b.forEach((function(e){c(t,o(e.documentation)),t.write(e.name+": "+u(e,m)).write(",").newLine()}))})).write("))")}}]})}h.formatText({indentSize:2,convertTabsToSpaces:!0,semicolons:i.SemicolonPreference.Remove})})),n.save()}}); | ||
//# sourceMappingURL=zod-prisma.cjs.production.min.js.map |
@@ -5,2 +5,3 @@ import path from 'path'; | ||
import { SemicolonPreference } from 'typescript'; | ||
import z from 'zod'; | ||
@@ -109,2 +110,9 @@ var getJSDocs = function getJSDocs(docString) { | ||
var configSchema = /*#__PURE__*/z.object({ | ||
relationModel: /*#__PURE__*/z["enum"](['default', 'true', 'false'])["default"]('true').transform(function (val) { | ||
return val === 'default' ? val : Boolean(val); | ||
}), | ||
modelSuffix: /*#__PURE__*/z.string()["default"]('Model'), | ||
modelCase: /*#__PURE__*/z["enum"](['PascalCase', 'camelCase'])["default"]('PascalCase') | ||
}); | ||
generatorHandler({ | ||
@@ -127,8 +135,8 @@ onManifest: function onManifest() { | ||
}); | ||
var _options$generator$co = options.generator.config, | ||
relationModel = _options$generator$co.relationModel, | ||
_options$generator$co2 = _options$generator$co.modelSuffix, | ||
modelSuffix = _options$generator$co2 === void 0 ? 'Model' : _options$generator$co2, | ||
_options$generator$co3 = _options$generator$co.modelCase, | ||
modelCase = _options$generator$co3 === void 0 ? 'PascalCase' : _options$generator$co3; | ||
var parsedConfig = configSchema.safeParse(options.generator.config); | ||
if (!parsedConfig.success) throw new Error('Incorrect config provided. Please check the values you provided and try again.'); | ||
var _parsedConfig$data = parsedConfig.data, | ||
relationModel = _parsedConfig$data.relationModel, | ||
modelSuffix = _parsedConfig$data.modelSuffix, | ||
modelCase = _parsedConfig$data.modelCase; | ||
@@ -151,3 +159,3 @@ var formatModelName = function formatModelName(name, prefix) { | ||
models.forEach(function (model) { | ||
var _prismaClient$output; | ||
var _prismaClient$output, _relativePath; | ||
@@ -178,5 +186,7 @@ indexSource.addExportDeclaration({ | ||
}); | ||
var relativePath = prismaClient != null && (_prismaClient$output = prismaClient.output) != null && _prismaClient$output.value ? path.relative(outputPath, prismaClient.output.value) : null; | ||
if (relativePath && !(relativePath.startsWith('./') || relativePath.startsWith('../'))) relativePath = "./" + relativePath; | ||
sourceFile.addImportDeclaration({ | ||
kind: StructureKind.ImportDeclaration, | ||
moduleSpecifier: prismaClient != null && (_prismaClient$output = prismaClient.output) != null && _prismaClient$output.value ? path.relative(outputPath, prismaClient.output.value) : '@prisma/client', | ||
moduleSpecifier: (_relativePath = relativePath) != null ? _relativePath : '@prisma/client', | ||
namedImports: [model.name].concat(enumFields.map(function (f) { | ||
@@ -183,0 +193,0 @@ return f.type; |
{ | ||
"version": "0.3.0", | ||
"version": "0.3.1", | ||
"license": "MIT", | ||
@@ -46,8 +46,9 @@ "description": "A Prisma generator that creates Zod schemas for all of your models", | ||
"resolutions": { | ||
"eslint": "^7.17.0" | ||
"eslint": "^7.17.0", | ||
"typescript": "4.5.4" | ||
}, | ||
"devDependencies": { | ||
"@types/fs-extra": "^9.0.11", | ||
"@typescript-eslint/eslint-plugin": "^4.33.0", | ||
"@typescript-eslint/parser": "^4.33.0", | ||
"@typescript-eslint/eslint-plugin": "^5.7.0", | ||
"@typescript-eslint/parser": "^5.7.0", | ||
"eslint": "^7.17.0", | ||
@@ -65,3 +66,3 @@ "eslint-config-react-app": "^6.0.0", | ||
"tslib": "^2.2.0", | ||
"typescript": "^4.4.4", | ||
"typescript": "^4.5.4", | ||
"zod": "^3.11.6" | ||
@@ -68,0 +69,0 @@ }, |
@@ -23,2 +23,3 @@ <!-- | ||
--> | ||
[![NPM][npm-shield]][npm-url] | ||
[![Contributors][contributors-shield]][contributors-url] | ||
@@ -74,3 +75,9 @@ [![Forks][forks-shield]][forks-url] | ||
</li> | ||
<li><a href="#usage">Usage</a></li> | ||
<li><a href="#usage">Usage</a> | ||
<ul> | ||
<li><a href="#jsdoc-generation">JSDoc Generation</a></li> | ||
<li><a href="#extending-zod-fields">Extending Zod Fields</a></li> | ||
</ul> | ||
</li> | ||
<li><a href="#examples">Examples</a></li> | ||
<li><a href="#roadmap">Roadmap</a></li> | ||
@@ -146,3 +153,71 @@ <li><a href="#contributing">Contributing</a></li> | ||
> TODO | ||
### JSDoc Generation | ||
[Rich-comments](https://www.prisma.io/docs/concepts/components/prisma-schema#comments) | ||
in the Prisma schema will be transformed into JSDoc for the associated fields: | ||
> _Note: make sure to use a triple-slash. Double-slash comments won't be processed._ | ||
```graphql | ||
model Post { | ||
/// The unique identifier for the post | ||
/// @default {Generated by database} | ||
id String @id @default(uuid()) | ||
/// A brief title that describes the contents of the post | ||
title String | ||
/// The actual contents of the post. | ||
contents String | ||
} | ||
``` | ||
Generated code: | ||
```ts | ||
export const PostModel = z.object({ | ||
/** | ||
* The unique identifier for the post | ||
* @default {Generated by database} | ||
*/ | ||
id: z.string().uuid(), | ||
/** | ||
* A brief title that describes the contents of the post | ||
*/ | ||
title: z.string(), | ||
/** | ||
* The actual contents of the post. | ||
*/ | ||
contents: z.string(), | ||
}) | ||
``` | ||
### Extending Zod Fields | ||
You can also use the `@zod` keyword in rich-comments in the Prisma schema | ||
to extend your Zod schema fields: | ||
```graphql | ||
model Post { | ||
id String @id @default(uuid()) /// @zod.uuid() | ||
/// @zod.max(255, { message: "The title must be shorter than 256 characters" }) | ||
title String | ||
contents String /// @zod.max(10240) | ||
} | ||
``` | ||
Generated code: | ||
```ts | ||
export const PostModel = z.object({ | ||
id: z.string().uuid(), | ||
title: z.string().max(255, { message: "The title must be shorter than 256 characters" }), | ||
contents: z.string().max(10240), | ||
}) | ||
``` | ||
## Examples | ||
<!-- Use this space to show useful examples of how a project can be used. Additional screenshots, code examples and demos work well in this space. You may also link to more resources. --> | ||
@@ -193,2 +268,4 @@ | ||
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links --> | ||
[npm-shield]: https://img.shields.io/npm/v/zod-prisma?style=for-the-badge | ||
[npm-url]: https://www.npmjs.com/package/zod-prisma | ||
[contributors-shield]: https://img.shields.io/github/contributors/CarterGrimmeisen/zod-prisma.svg?style=for-the-badge | ||
@@ -195,0 +272,0 @@ [contributors-url]: https://github.com/CarterGrimmeisen/zod-prisma/graphs/contributors |
@@ -8,8 +8,12 @@ import path from 'path' | ||
import { writeArray } from './util' | ||
import z from 'zod' | ||
interface Config { | ||
relationModel: boolean | 'default' | ||
modelSuffix?: string | ||
modelCase?: 'PascalCase' | 'camelCase' | ||
} | ||
const configSchema = z.object({ | ||
relationModel: z | ||
.enum(['default', 'true', 'false']) | ||
.default('true') | ||
.transform((val) => (val === 'default' ? val : Boolean(val))), | ||
modelSuffix: z.string().default('Model'), | ||
modelCase: z.enum(['PascalCase', 'camelCase']).default('PascalCase'), | ||
}) | ||
@@ -36,8 +40,10 @@ generatorHandler({ | ||
const { | ||
relationModel, | ||
modelSuffix = 'Model', | ||
modelCase = 'PascalCase', | ||
} = options.generator.config as unknown as Config | ||
const parsedConfig = configSchema.safeParse(options.generator.config) | ||
if (!parsedConfig.success) | ||
throw new Error( | ||
'Incorrect config provided. Please check the values you provided and try again.' | ||
) | ||
const { relationModel, modelSuffix, modelCase } = parsedConfig.data | ||
const formatModelName = (name: string, prefix = '') => { | ||
@@ -97,7 +103,17 @@ if (modelCase === 'camelCase') { | ||
let relativePath = prismaClient?.output?.value | ||
? path.relative(outputPath, prismaClient.output.value) | ||
: null | ||
if ( | ||
relativePath && | ||
!( | ||
relativePath.startsWith('./') || | ||
relativePath.startsWith('../') | ||
) | ||
) | ||
relativePath = `./${relativePath}` | ||
sourceFile.addImportDeclaration({ | ||
kind: StructureKind.ImportDeclaration, | ||
moduleSpecifier: prismaClient?.output?.value | ||
? path.relative(outputPath, prismaClient.output.value) | ||
: '@prisma/client', | ||
moduleSpecifier: relativePath ?? '@prisma/client', | ||
namedImports: [model.name, ...enumFields.map((f) => f.type)], | ||
@@ -104,0 +120,0 @@ }) |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
99722
826
276