@mirite/zod-to-mongoose 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,8 +13,8 @@ import type { ZodUnion } from 'zod';
13
13
  export declare type Check = "";
14
14
 
15
15
  export declare function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>, modelName: string, connection: Mongoose.Connection): {
16
- schema: Mongoose.Schema;
17
16
  model: Mongoose.Model<z.infer<typeof zodObject>>;
17
+ schema: Mongoose.Schema;
18
18
  };
19
19
 
20
20
  export declare function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;
@@ -26,12 +26,12 @@ export declare type Field = {
26
26
  };
27
27
 
28
28
  export declare type FieldDefinition = {
29
- typeName: string;
30
- innerType?: Field;
31
29
  description: string | undefined;
30
+ innerType?: Field;
31
+ typeName: string;
32
32
  };
33
33
 
34
- declare type SupportedPrimitive = ZodString | ZodNumber | ZodBoolean | ZodDate;
34
+ declare type SupportedPrimitive = ZodBoolean | ZodDate | ZodNumber | ZodString;
35
35
 
36
36
  export declare type SupportedType = SupportedPrimitive | ZodDefault<ZodTypeAny> | ZodObject<ZodRawShape> | ZodUnion<readonly [ZodTypeAny, ...ZodTypeAny[]]>;
37
37
 
@@ -13,8 +13,8 @@ import type { ZodUnion } from 'zod';
13
13
  export declare type Check = "";
14
14
 
15
15
  export declare function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>, modelName: string, connection: Mongoose.Connection): {
16
- schema: Mongoose.Schema;
17
16
  model: Mongoose.Model<z.infer<typeof zodObject>>;
17
+ schema: Mongoose.Schema;
18
18
  };
19
19
 
20
20
  export declare function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;
@@ -26,12 +26,12 @@ export declare type Field = {
26
26
  };
27
27
 
28
28
  export declare type FieldDefinition = {
29
- typeName: string;
30
- innerType?: Field;
31
29
  description: string | undefined;
30
+ innerType?: Field;
31
+ typeName: string;
32
32
  };
33
33
 
34
- declare type SupportedPrimitive = ZodString | ZodNumber | ZodBoolean | ZodDate;
34
+ declare type SupportedPrimitive = ZodBoolean | ZodDate | ZodNumber | ZodString;
35
35
 
36
36
  export declare type SupportedType = SupportedPrimitive | ZodDefault<ZodTypeAny> | ZodObject<ZodRawShape> | ZodUnion<readonly [ZodTypeAny, ...ZodTypeAny[]]>;
37
37
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var s=Object.create;var d=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var m=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty;var S=(e,o)=>{for(var t in o)d(e,t,{get:o[t],enumerable:!0})},r=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let a of l(o))!h.call(e,a)&&a!==t&&d(e,a,{get:()=>o[a],enumerable:!(n=u(o,a))||n.enumerable});return e};var y=(e,o,t)=>(t=e!=null?s(m(e)):{},r(o||!e||!e.__esModule?d(t,"default",{value:e,enumerable:!0}):t,e)),b=e=>r(d({},"__esModule",{value:!0}),e);var w={};S(w,{createSchema:()=>p});module.exports=b(w);var c=y(require("mongoose"),1);function p(e,o,t){let n={};for(let i in e.shape){let f=e.shape[i];n[i]=T(i,f)}let a=new c.Schema(n);return!t||!o?a:{schema:a,model:t.model(o,a)}}function Z(e){return e._def.typeName==="ZodObject"}function T(e,o){let t=g(o),n;switch(t.definition._def.typeName){case"ZodString":n=String;break;case"ZodNumber":n=Number;break;case"ZodBoolean":n=Boolean;break;case"ZodDate":n=Date;break;case"ZodObject":break;case"ZodUnion":n={};break;default:throw new TypeError(`Unsupported type: ${e}`)}return Z(t.definition)&&(n=p(t.definition)),t.defaultValue?{type:n,default:t.defaultValue}:n}function g(e){let o=e,t=!1,n;for(;"innerType"in o._def;)"defaultValue"in o._def&&(n=o._def.defaultValue()),o=o._def.innerType;return{definition:o,optional:t,defaultValue:n}}0&&(module.exports={createSchema});
1
+ "use strict";var s=Object.create;var d=Object.defineProperty;var u=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var m=Object.getPrototypeOf,h=Object.prototype.hasOwnProperty;var S=(e,o)=>{for(var t in o)d(e,t,{get:o[t],enumerable:!0})},r=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let a of l(o))!h.call(e,a)&&a!==t&&d(e,a,{get:()=>o[a],enumerable:!(n=u(o,a))||n.enumerable});return e};var y=(e,o,t)=>(t=e!=null?s(m(e)):{},r(o||!e||!e.__esModule?d(t,"default",{value:e,enumerable:!0}):t,e)),b=e=>r(d({},"__esModule",{value:!0}),e);var w={};S(w,{createSchema:()=>p});module.exports=b(w);var c=y(require("mongoose"),1);function p(e,o,t){let n={};for(let i in e.shape){let f=e.shape[i];n[i]=Z(i,f)}let a=new c.Schema(n);return!t||!o?a:{model:t.model(o,a),schema:a}}function Z(e,o){let t=g(o),n;switch(t.definition._def.typeName){case"ZodBoolean":n=Boolean;break;case"ZodDate":n=Date;break;case"ZodNumber":n=Number;break;case"ZodObject":break;case"ZodString":n=String;break;case"ZodUnion":n={};break;default:throw new TypeError(`Unsupported type: ${e}`)}return T(t.definition)&&(n=p(t.definition)),t.defaultValue?{default:t.defaultValue,type:n}:n}function T(e){return e._def.typeName==="ZodObject"}function g(e){let o=e,t=!1,n;for(;"innerType"in o._def;)"defaultValue"in o._def&&(n=o._def.defaultValue()),o=o._def.innerType;return{defaultValue:n,definition:o,optional:t}}0&&(module.exports={createSchema});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import * as Mongoose from \"mongoose\";\nimport type { SchemaDefinition } from \"mongoose\";\nimport type { z, ZodObject, ZodRawShape } from \"zod\";\n\nimport type { SupportedType } from \"./types\";\n\nexport function createSchema<T extends ZodRawShape>(\n zodObject: ZodObject<T>,\n modelName: string,\n connection: Mongoose.Connection,\n): { schema: Mongoose.Schema; model: Mongoose.Model<z.infer<typeof zodObject>> };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @template T The Zod schema shape.\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n zodObject: ZodObject<T>,\n modelName?: string,\n connection?: Mongoose.Connection,\n): Mongoose.Schema | { schema: Mongoose.Schema; model: Mongoose.Model<z.infer<typeof zodObject>> } {\n const convertedShape: Partial<SchemaDefinition> = {};\n for (const key in zodObject.shape) {\n const zodField = zodObject.shape[key];\n convertedShape[key] = convertField(key, zodField);\n }\n const schema = new Mongoose.Schema(convertedShape);\n if (!connection || !modelName) return schema;\n return { schema, model: connection.model<z.infer<typeof zodObject>>(modelName, schema) };\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n return definition._def.typeName === \"ZodObject\";\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @template T The Zod schema shape.\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n * @throws TypeError If the type is not supported.\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]) {\n const unwrappedData = unwrapType(zodField);\n let coreType;\n switch (unwrappedData.definition._def.typeName) {\n case \"ZodString\":\n coreType = String;\n break;\n case \"ZodNumber\":\n coreType = Number;\n break;\n case \"ZodBoolean\":\n coreType = Boolean;\n break;\n case \"ZodDate\":\n coreType = Date;\n break;\n case \"ZodObject\":\n break;\n case \"ZodUnion\":\n coreType = {};\n break;\n default:\n throw new TypeError(`Unsupported type: ${type}`);\n }\n if (isZodObject(unwrappedData.definition)) {\n coreType = createSchema(unwrappedData.definition);\n }\n\n if (!unwrappedData.defaultValue) {\n return coreType;\n }\n return {\n type: coreType,\n default: unwrappedData.defaultValue,\n };\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): { definition: SupportedType; optional: boolean; defaultValue?: unknown } {\n let definition = data;\n const optional = false;\n let defaultValue = undefined;\n while (\"innerType\" in definition._def) {\n if (\"defaultValue\" in definition._def) {\n defaultValue = definition._def.defaultValue();\n }\n definition = definition._def.innerType;\n }\n return { definition, optional, defaultValue };\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAA0B,yBAqBnB,SAASF,EACZG,EACAC,EACAC,EAC+F,CAC/F,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAC/B,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,CAAQ,CACpD,CACA,IAAME,EAAS,IAAa,SAAOJ,CAAc,EACjD,MAAI,CAACD,GAAc,CAACD,EAAkBM,EAC/B,CAAE,OAAAA,EAAQ,MAAOL,EAAW,MAAiCD,EAAWM,CAAM,CAAE,CAC3F,CAQA,SAASC,EAAYC,EAAiE,CAClF,OAAOA,EAAW,KAAK,WAAa,WACxC,CAWA,SAASH,EAAoCI,EAAcL,EAAuC,CAC9F,IAAMM,EAAgBC,EAAWP,CAAQ,EACrCQ,EACJ,OAAQF,EAAc,WAAW,KAAK,SAAU,CAC5C,IAAK,YACDE,EAAW,OACX,MACJ,IAAK,YACDA,EAAW,OACX,MACJ,IAAK,aACDA,EAAW,QACX,MACJ,IAAK,UACDA,EAAW,KACX,MACJ,IAAK,YACD,MACJ,IAAK,WACDA,EAAW,CAAC,EACZ,MACJ,QACI,MAAM,IAAI,UAAU,qBAAqBH,CAAI,EAAE,CACvD,CAKA,OAJIF,EAAYG,EAAc,UAAU,IACpCE,EAAWhB,EAAac,EAAc,UAAU,GAG/CA,EAAc,aAGZ,CACH,KAAME,EACN,QAASF,EAAc,YAC3B,EALWE,CAMf,CAQA,SAASD,EAAWE,EAA+F,CAC/G,IAAIL,EAAaK,EACXC,EAAW,GACbC,EACJ,KAAO,cAAeP,EAAW,MACzB,iBAAkBA,EAAW,OAC7BO,EAAeP,EAAW,KAAK,aAAa,GAEhDA,EAAaA,EAAW,KAAK,UAEjC,MAAO,CAAE,WAAAA,EAAY,SAAAM,EAAU,aAAAC,CAAa,CAChD","names":["index_exports","__export","createSchema","__toCommonJS","Mongoose","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","isZodObject","definition","type","unwrappedData","unwrapType","coreType","data","optional","defaultValue"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { SchemaDefinition } from \"mongoose\";\nimport type { z, ZodObject, ZodRawShape } from \"zod\";\n\nimport * as Mongoose from \"mongoose\";\n\nimport type { SupportedType } from \"./types\";\n\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName: string,\n\tconnection: Mongoose.Connection,\n): { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema; };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @template T The Zod schema shape.\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName?: string,\n\tconnection?: Mongoose.Connection,\n): Mongoose.Schema | { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema; } {\n\tconst convertedShape: Partial<SchemaDefinition> = {};\n\tfor (const key in zodObject.shape) {\n\t\tconst zodField = zodObject.shape[key];\n\t\tconvertedShape[key] = convertField(key, zodField);\n\t}\n\tconst schema = new Mongoose.Schema(convertedShape);\n\tif (!connection || !modelName) return schema;\n\treturn { model: connection.model<z.infer<typeof zodObject>>(modelName, schema), schema };\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @template T The Zod schema shape.\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n * @throws TypeError If the type is not supported.\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]) {\n\tconst unwrappedData = unwrapType(zodField);\n\tlet coreType;\n\tswitch (unwrappedData.definition._def.typeName) {\n\t\tcase \"ZodBoolean\":\n\t\t\tcoreType = Boolean;\n\t\t\tbreak;\n\t\tcase \"ZodDate\":\n\t\t\tcoreType = Date;\n\t\t\tbreak;\n\t\tcase \"ZodNumber\":\n\t\t\tcoreType = Number;\n\t\t\tbreak;\n\t\tcase \"ZodObject\":\n\t\t\tbreak;\n\t\tcase \"ZodString\":\n\t\t\tcoreType = String;\n\t\t\tbreak;\n\t\tcase \"ZodUnion\":\n\t\t\tcoreType = {};\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(`Unsupported type: ${type}`);\n\t}\n\tif (isZodObject(unwrappedData.definition)) {\n\t\tcoreType = createSchema(unwrappedData.definition);\n\t}\n\n\tif (!unwrappedData.defaultValue) {\n\t\treturn coreType;\n\t}\n\treturn {\n\t\tdefault: unwrappedData.defaultValue,\n\t\ttype: coreType,\n\t};\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n\treturn definition._def.typeName === \"ZodObject\";\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): { defaultValue?: unknown; definition: SupportedType; optional: boolean; } {\n\tlet definition = data;\n\tconst optional = false;\n\tlet defaultValue = undefined;\n\twhile (\"innerType\" in definition._def) {\n\t\tif (\"defaultValue\" in definition._def) {\n\t\t\tdefaultValue = definition._def.defaultValue();\n\t\t}\n\t\tdefinition = definition._def.innerType;\n\t}\n\treturn { defaultValue, definition, optional };\n}\n"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,kBAAAE,IAAA,eAAAC,EAAAH,GAGA,IAAAI,EAA0B,yBAmBnB,SAASF,EACfG,EACAC,EACAC,EACmG,CACnG,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAClC,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,CAAQ,CACjD,CACA,IAAME,EAAS,IAAa,SAAOJ,CAAc,EACjD,MAAI,CAACD,GAAc,CAACD,EAAkBM,EAC/B,CAAE,MAAOL,EAAW,MAAiCD,EAAWM,CAAM,EAAG,OAAAA,CAAO,CACxF,CAWA,SAASD,EAAoCE,EAAcH,EAAuC,CACjG,IAAMI,EAAgBC,EAAWL,CAAQ,EACrCM,EACJ,OAAQF,EAAc,WAAW,KAAK,SAAU,CAC/C,IAAK,aACJE,EAAW,QACX,MACD,IAAK,UACJA,EAAW,KACX,MACD,IAAK,YACJA,EAAW,OACX,MACD,IAAK,YACJ,MACD,IAAK,YACJA,EAAW,OACX,MACD,IAAK,WACJA,EAAW,CAAC,EACZ,MACD,QACC,MAAM,IAAI,UAAU,qBAAqBH,CAAI,EAAE,CACjD,CAKA,OAJII,EAAYH,EAAc,UAAU,IACvCE,EAAWd,EAAaY,EAAc,UAAU,GAG5CA,EAAc,aAGZ,CACN,QAASA,EAAc,aACvB,KAAME,CACP,EALQA,CAMT,CAQA,SAASC,EAAYC,EAAiE,CACrF,OAAOA,EAAW,KAAK,WAAa,WACrC,CAQA,SAASH,EAAWI,EAAgG,CACnH,IAAID,EAAaC,EACXC,EAAW,GACbC,EACJ,KAAO,cAAeH,EAAW,MAC5B,iBAAkBA,EAAW,OAChCG,EAAeH,EAAW,KAAK,aAAa,GAE7CA,EAAaA,EAAW,KAAK,UAE9B,MAAO,CAAE,aAAAG,EAAc,WAAAH,EAAY,SAAAE,CAAS,CAC7C","names":["index_exports","__export","createSchema","__toCommonJS","Mongoose","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","type","unwrappedData","unwrapType","coreType","isZodObject","definition","data","optional","defaultValue"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import*as i from"mongoose";function c(n,o,t){let e={};for(let d in n.shape){let r=n.shape[d];e[d]=f(d,r)}let a=new i.Schema(e);return!t||!o?a:{schema:a,model:t.model(o,a)}}function p(n){return n._def.typeName==="ZodObject"}function f(n,o){let t=s(o),e;switch(t.definition._def.typeName){case"ZodString":e=String;break;case"ZodNumber":e=Number;break;case"ZodBoolean":e=Boolean;break;case"ZodDate":e=Date;break;case"ZodObject":break;case"ZodUnion":e={};break;default:throw new TypeError(`Unsupported type: ${n}`)}return p(t.definition)&&(e=c(t.definition)),t.defaultValue?{type:e,default:t.defaultValue}:e}function s(n){let o=n,t=!1,e;for(;"innerType"in o._def;)"defaultValue"in o._def&&(e=o._def.defaultValue()),o=o._def.innerType;return{definition:o,optional:t,defaultValue:e}}export{c as createSchema};
1
+ import*as i from"mongoose";function c(n,o,t){let e={};for(let d in n.shape){let r=n.shape[d];e[d]=p(d,r)}let a=new i.Schema(e);return!t||!o?a:{model:t.model(o,a),schema:a}}function p(n,o){let t=s(o),e;switch(t.definition._def.typeName){case"ZodBoolean":e=Boolean;break;case"ZodDate":e=Date;break;case"ZodNumber":e=Number;break;case"ZodObject":break;case"ZodString":e=String;break;case"ZodUnion":e={};break;default:throw new TypeError(`Unsupported type: ${n}`)}return f(t.definition)&&(e=c(t.definition)),t.defaultValue?{default:t.defaultValue,type:e}:e}function f(n){return n._def.typeName==="ZodObject"}function s(n){let o=n,t=!1,e;for(;"innerType"in o._def;)"defaultValue"in o._def&&(e=o._def.defaultValue()),o=o._def.innerType;return{defaultValue:e,definition:o,optional:t}}export{c as createSchema};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import * as Mongoose from \"mongoose\";\nimport type { SchemaDefinition } from \"mongoose\";\nimport type { z, ZodObject, ZodRawShape } from \"zod\";\n\nimport type { SupportedType } from \"./types\";\n\nexport function createSchema<T extends ZodRawShape>(\n zodObject: ZodObject<T>,\n modelName: string,\n connection: Mongoose.Connection,\n): { schema: Mongoose.Schema; model: Mongoose.Model<z.infer<typeof zodObject>> };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @template T The Zod schema shape.\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n zodObject: ZodObject<T>,\n modelName?: string,\n connection?: Mongoose.Connection,\n): Mongoose.Schema | { schema: Mongoose.Schema; model: Mongoose.Model<z.infer<typeof zodObject>> } {\n const convertedShape: Partial<SchemaDefinition> = {};\n for (const key in zodObject.shape) {\n const zodField = zodObject.shape[key];\n convertedShape[key] = convertField(key, zodField);\n }\n const schema = new Mongoose.Schema(convertedShape);\n if (!connection || !modelName) return schema;\n return { schema, model: connection.model<z.infer<typeof zodObject>>(modelName, schema) };\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n return definition._def.typeName === \"ZodObject\";\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @template T The Zod schema shape.\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n * @throws TypeError If the type is not supported.\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]) {\n const unwrappedData = unwrapType(zodField);\n let coreType;\n switch (unwrappedData.definition._def.typeName) {\n case \"ZodString\":\n coreType = String;\n break;\n case \"ZodNumber\":\n coreType = Number;\n break;\n case \"ZodBoolean\":\n coreType = Boolean;\n break;\n case \"ZodDate\":\n coreType = Date;\n break;\n case \"ZodObject\":\n break;\n case \"ZodUnion\":\n coreType = {};\n break;\n default:\n throw new TypeError(`Unsupported type: ${type}`);\n }\n if (isZodObject(unwrappedData.definition)) {\n coreType = createSchema(unwrappedData.definition);\n }\n\n if (!unwrappedData.defaultValue) {\n return coreType;\n }\n return {\n type: coreType,\n default: unwrappedData.defaultValue,\n };\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): { definition: SupportedType; optional: boolean; defaultValue?: unknown } {\n let definition = data;\n const optional = false;\n let defaultValue = undefined;\n while (\"innerType\" in definition._def) {\n if (\"defaultValue\" in definition._def) {\n defaultValue = definition._def.defaultValue();\n }\n definition = definition._def.innerType;\n }\n return { definition, optional, defaultValue };\n}\n"],"mappings":"AAAA,UAAYA,MAAc,WAqBnB,SAASC,EACZC,EACAC,EACAC,EAC+F,CAC/F,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAC/B,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,CAAQ,CACpD,CACA,IAAME,EAAS,IAAa,SAAOJ,CAAc,EACjD,MAAI,CAACD,GAAc,CAACD,EAAkBM,EAC/B,CAAE,OAAAA,EAAQ,MAAOL,EAAW,MAAiCD,EAAWM,CAAM,CAAE,CAC3F,CAQA,SAASC,EAAYC,EAAiE,CAClF,OAAOA,EAAW,KAAK,WAAa,WACxC,CAWA,SAASH,EAAoCI,EAAcL,EAAuC,CAC9F,IAAMM,EAAgBC,EAAWP,CAAQ,EACrCQ,EACJ,OAAQF,EAAc,WAAW,KAAK,SAAU,CAC5C,IAAK,YACDE,EAAW,OACX,MACJ,IAAK,YACDA,EAAW,OACX,MACJ,IAAK,aACDA,EAAW,QACX,MACJ,IAAK,UACDA,EAAW,KACX,MACJ,IAAK,YACD,MACJ,IAAK,WACDA,EAAW,CAAC,EACZ,MACJ,QACI,MAAM,IAAI,UAAU,qBAAqBH,CAAI,EAAE,CACvD,CAKA,OAJIF,EAAYG,EAAc,UAAU,IACpCE,EAAWd,EAAaY,EAAc,UAAU,GAG/CA,EAAc,aAGZ,CACH,KAAME,EACN,QAASF,EAAc,YAC3B,EALWE,CAMf,CAQA,SAASD,EAAWE,EAA+F,CAC/G,IAAIL,EAAaK,EACXC,EAAW,GACbC,EACJ,KAAO,cAAeP,EAAW,MACzB,iBAAkBA,EAAW,OAC7BO,EAAeP,EAAW,KAAK,aAAa,GAEhDA,EAAaA,EAAW,KAAK,UAEjC,MAAO,CAAE,WAAAA,EAAY,SAAAM,EAAU,aAAAC,CAAa,CAChD","names":["Mongoose","createSchema","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","isZodObject","definition","type","unwrappedData","unwrapType","coreType","data","optional","defaultValue"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { SchemaDefinition } from \"mongoose\";\nimport type { z, ZodObject, ZodRawShape } from \"zod\";\n\nimport * as Mongoose from \"mongoose\";\n\nimport type { SupportedType } from \"./types\";\n\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName: string,\n\tconnection: Mongoose.Connection,\n): { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema; };\nexport function createSchema<T extends ZodRawShape>(zodObject: ZodObject<T>): Mongoose.Schema;\n/**\n * Create a Mongoose schema from a Zod shape\n *\n * @template T The Zod schema shape.\n * @param zodObject The Zod shape to create the schema from\n * @param modelName The unique name to assign to the model\n * @param connection The Mongoose connection to create the model from\n * @returns The Mongoose schema\n */\nexport function createSchema<T extends ZodRawShape>(\n\tzodObject: ZodObject<T>,\n\tmodelName?: string,\n\tconnection?: Mongoose.Connection,\n): Mongoose.Schema | { model: Mongoose.Model<z.infer<typeof zodObject>>; schema: Mongoose.Schema; } {\n\tconst convertedShape: Partial<SchemaDefinition> = {};\n\tfor (const key in zodObject.shape) {\n\t\tconst zodField = zodObject.shape[key];\n\t\tconvertedShape[key] = convertField(key, zodField);\n\t}\n\tconst schema = new Mongoose.Schema(convertedShape);\n\tif (!connection || !modelName) return schema;\n\treturn { model: connection.model<z.infer<typeof zodObject>>(modelName, schema), schema };\n}\n\n/**\n * Convert a Zod field to a Mongoose type\n *\n * @template T The Zod schema shape.\n * @param type The key of the field\n * @param zodField The Zod field to convert\n * @returns The Mongoose type\n * @throws TypeError If the type is not supported.\n */\nfunction convertField<T extends ZodRawShape>(type: string, zodField: T[Extract<keyof T, string>]) {\n\tconst unwrappedData = unwrapType(zodField);\n\tlet coreType;\n\tswitch (unwrappedData.definition._def.typeName) {\n\t\tcase \"ZodBoolean\":\n\t\t\tcoreType = Boolean;\n\t\t\tbreak;\n\t\tcase \"ZodDate\":\n\t\t\tcoreType = Date;\n\t\t\tbreak;\n\t\tcase \"ZodNumber\":\n\t\t\tcoreType = Number;\n\t\t\tbreak;\n\t\tcase \"ZodObject\":\n\t\t\tbreak;\n\t\tcase \"ZodString\":\n\t\t\tcoreType = String;\n\t\t\tbreak;\n\t\tcase \"ZodUnion\":\n\t\t\tcoreType = {};\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new TypeError(`Unsupported type: ${type}`);\n\t}\n\tif (isZodObject(unwrappedData.definition)) {\n\t\tcoreType = createSchema(unwrappedData.definition);\n\t}\n\n\tif (!unwrappedData.defaultValue) {\n\t\treturn coreType;\n\t}\n\treturn {\n\t\tdefault: unwrappedData.defaultValue,\n\t\ttype: coreType,\n\t};\n}\n\n/**\n * Check if a Zod definition is an object\n *\n * @param definition The Zod definition to check\n * @returns Whether the definition is an object\n */\nfunction isZodObject(definition: SupportedType): definition is ZodObject<ZodRawShape> {\n\treturn definition._def.typeName === \"ZodObject\";\n}\n\n/**\n * Takes a complex type and returns the inner type definition along with the default if present.\n *\n * @param data The type data to unwrap.\n * @returns The inner type data along with the default if present.\n */\nfunction unwrapType(data: SupportedType): { defaultValue?: unknown; definition: SupportedType; optional: boolean; } {\n\tlet definition = data;\n\tconst optional = false;\n\tlet defaultValue = undefined;\n\twhile (\"innerType\" in definition._def) {\n\t\tif (\"defaultValue\" in definition._def) {\n\t\t\tdefaultValue = definition._def.defaultValue();\n\t\t}\n\t\tdefinition = definition._def.innerType;\n\t}\n\treturn { defaultValue, definition, optional };\n}\n"],"mappings":"AAGA,UAAYA,MAAc,WAmBnB,SAASC,EACfC,EACAC,EACAC,EACmG,CACnG,IAAMC,EAA4C,CAAC,EACnD,QAAWC,KAAOJ,EAAU,MAAO,CAClC,IAAMK,EAAWL,EAAU,MAAMI,CAAG,EACpCD,EAAeC,CAAG,EAAIE,EAAaF,EAAKC,CAAQ,CACjD,CACA,IAAME,EAAS,IAAa,SAAOJ,CAAc,EACjD,MAAI,CAACD,GAAc,CAACD,EAAkBM,EAC/B,CAAE,MAAOL,EAAW,MAAiCD,EAAWM,CAAM,EAAG,OAAAA,CAAO,CACxF,CAWA,SAASD,EAAoCE,EAAcH,EAAuC,CACjG,IAAMI,EAAgBC,EAAWL,CAAQ,EACrCM,EACJ,OAAQF,EAAc,WAAW,KAAK,SAAU,CAC/C,IAAK,aACJE,EAAW,QACX,MACD,IAAK,UACJA,EAAW,KACX,MACD,IAAK,YACJA,EAAW,OACX,MACD,IAAK,YACJ,MACD,IAAK,YACJA,EAAW,OACX,MACD,IAAK,WACJA,EAAW,CAAC,EACZ,MACD,QACC,MAAM,IAAI,UAAU,qBAAqBH,CAAI,EAAE,CACjD,CAKA,OAJII,EAAYH,EAAc,UAAU,IACvCE,EAAWZ,EAAaU,EAAc,UAAU,GAG5CA,EAAc,aAGZ,CACN,QAASA,EAAc,aACvB,KAAME,CACP,EALQA,CAMT,CAQA,SAASC,EAAYC,EAAiE,CACrF,OAAOA,EAAW,KAAK,WAAa,WACrC,CAQA,SAASH,EAAWI,EAAgG,CACnH,IAAID,EAAaC,EACXC,EAAW,GACbC,EACJ,KAAO,cAAeH,EAAW,MAC5B,iBAAkBA,EAAW,OAChCG,EAAeH,EAAW,KAAK,aAAa,GAE7CA,EAAaA,EAAW,KAAK,UAE9B,MAAO,CAAE,aAAAG,EAAc,WAAAH,EAAY,SAAAE,CAAS,CAC7C","names":["Mongoose","createSchema","zodObject","modelName","connection","convertedShape","key","zodField","convertField","schema","type","unwrappedData","unwrapType","coreType","isZodObject","definition","data","optional","defaultValue"]}
package/package.json CHANGED
@@ -1,60 +1,59 @@
1
1
  {
2
- "name": "@mirite/zod-to-mongoose",
3
- "license": "MIT",
4
- "version": "0.1.0",
5
- "description": "Package for creating mongoose schemas out of Zod schemas for type safety, and removing duplicate effort.",
6
- "type": "module",
7
- "repository": {
8
- "type": "git",
9
- "url": "git+https://github.com/mirite/zod-to-mongoose.git"
10
- },
11
- "author": {
12
- "name": "Jesse Conner",
13
- "email": "me@jesseconner.ca",
14
- "url": "https://jesseconner.ca"
15
- },
16
- "keywords": [
17
- "zod",
18
- "mongoose",
19
- "schema",
20
- "type",
21
- "type-safe"
22
- ],
23
- "issues": "https://github.com/mirite/zod-to-mongoose/issues",
24
- "exports": {
25
- ".": {
26
- "import": "./dist/index.js",
27
- "require": "./dist/index.cjs"
28
- }
29
- },
30
- "types": "./dist/_tsup-dts-rollup.d.ts",
31
- "files": [
32
- "dist"
33
- ],
34
- "scripts": {
35
- "build": "tsup",
36
- "check": "tsc --noEmit",
37
- "test": "vitest --run --coverage",
38
- "test:watch": "vitest --ui --coverage",
39
- "lint": "eslint --fix --cache",
40
- "format": "prettier --write --cache .",
41
- "release": "yarn build && npm publish"
42
- },
43
- "dependencies": {
44
- "mongoose": "^8.13.2",
45
- "zod": "^3.24.2"
46
- },
47
- "devDependencies": {
48
- "@microsoft/api-extractor": "^7.52.3",
49
- "@mirite/eslint-config-mirite": "^1.0.1",
50
- "@vitest/coverage-v8": "^3.1.1",
51
- "@vitest/ui": "^3.1.1",
52
- "eslint": "^9.24.0",
53
- "prettier": "^3.5.3",
54
- "prettier-plugin-jsdoc": "^1.3.2",
55
- "tsup": "^8.4.0",
56
- "typescript": "^5.8.3",
57
- "vitest": "^3.1.1"
58
- },
59
- "packageManager": "yarn@4.9.1"
2
+ "name": "@mirite/zod-to-mongoose",
3
+ "version": "0.1.1",
4
+ "description": "Package for creating mongoose schemas out of Zod schemas for type safety, and removing duplicate effort.",
5
+ "keywords": [
6
+ "zod",
7
+ "mongoose",
8
+ "schema",
9
+ "type",
10
+ "type-safe"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/mirite/zod-to-mongoose.git"
15
+ },
16
+ "license": "MIT",
17
+ "author": {
18
+ "name": "Jesse Conner",
19
+ "email": "me@jesseconner.ca",
20
+ "url": "https://jesseconner.ca"
21
+ },
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "import": "./dist/index.js",
26
+ "require": "./dist/index.cjs"
27
+ }
28
+ },
29
+ "types": "./dist/_tsup-dts-rollup.d.ts",
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "scripts": {
34
+ "build": "tsup",
35
+ "check": "tsc --noEmit",
36
+ "format": "prettier --write --cache .",
37
+ "lint": "eslint --fix --cache",
38
+ "release": "yarn build && npm publish",
39
+ "test": "vitest --run --coverage",
40
+ "test:watch": "vitest --ui --coverage"
41
+ },
42
+ "dependencies": {
43
+ "mongoose": "^8.16.3",
44
+ "zod": "^3.25.76"
45
+ },
46
+ "devDependencies": {
47
+ "@microsoft/api-extractor": "^7.52.8",
48
+ "@mirite/eslint-config-mirite": "^1.1.4",
49
+ "@vitest/coverage-v8": "^3.2.4",
50
+ "@vitest/ui": "^3.2.4",
51
+ "eslint": "^9.30.1",
52
+ "prettier": "^3.6.2",
53
+ "tsup": "^8.5.0",
54
+ "typescript": "^5.8.3",
55
+ "vitest": "^3.2.4"
56
+ },
57
+ "packageManager": "yarn@4.9.2",
58
+ "issues": "https://github.com/mirite/zod-to-mongoose/issues"
60
59
  }
package/readme.md CHANGED
@@ -18,18 +18,18 @@ Passing in a Zod schema will return a Mongoose schema.
18
18
  import { createSchema } from "@mirite/zod-to-mongoose";
19
19
 
20
20
  const schema = createSchema(
21
- z.object({
22
- name: z.string().optional().default("Bob"),
23
- age: z.number().default(3).optional(),
24
- isHappy: z.boolean().optional(),
25
- birthday: z.date().default(new Date()),
26
- }),
21
+ z.object({
22
+ name: z.string().optional().default("Bob"),
23
+ age: z.number().default(3).optional(),
24
+ isHappy: z.boolean().optional(),
25
+ birthday: z.date().default(new Date()),
26
+ }),
27
27
  );
28
28
 
29
29
  const model = mongoose.model("modelName", schema);
30
30
  const result = await model.create({
31
- isHappy: true,
32
- birthday: new Date("1980-01-01"),
31
+ isHappy: true,
32
+ birthday: new Date("1980-01-01"),
33
33
  });
34
34
  ```
35
35
 
@@ -41,19 +41,19 @@ If you pass a connection, the model will be created, registered with the connect
41
41
  import { createSchema } from "@mirite/zod-to-mongoose";
42
42
 
43
43
  const model = createSchema(
44
- z.object({
45
- name: z.string().optional().default("Bob"),
46
- age: z.number().default(3).optional(),
47
- isHappy: z.boolean().optional(),
48
- birthday: z.date().default(new Date()),
49
- }),
50
- "modelName", // The unique name to give the model
51
- connection, // Mongoose connection
44
+ z.object({
45
+ name: z.string().optional().default("Bob"),
46
+ age: z.number().default(3).optional(),
47
+ isHappy: z.boolean().optional(),
48
+ birthday: z.date().default(new Date()),
49
+ }),
50
+ "modelName", // The unique name to give the model
51
+ connection, // Mongoose connection
52
52
  );
53
53
 
54
54
  const result = await model.create({
55
- isHappy: true,
56
- birthday: new Date("1980-01-01"),
55
+ isHappy: true,
56
+ birthday: new Date("1980-01-01"),
57
57
  });
58
58
  ```
59
59