giddyinc / mongoose-to-swagger

Conversion library for transforming Mongoose schema objects into Swagger schema definitions.
MIT License
54 stars 29 forks source link

Add ref to connecting with components schema $ref #63

Open sendyputra opened 1 year ago

sendyputra commented 1 year ago

Hi! πŸ‘‹

Firstly, thanks for your work on this project! πŸ™‚

Today I used patch-package to patch mongoose-to-swagger@1.4.0 for the project I'm working on.

Here is the diff that solved my problem:

diff --git a/node_modules/mongoose-to-swagger/dist/index.js b/node_modules/mongoose-to-swagger/dist/index.js
index 453b96a..2b804f6 100644
--- a/node_modules/mongoose-to-swagger/dist/index.js
+++ b/node_modules/mongoose-to-swagger/dist/index.js
@@ -88,6 +88,9 @@ const defaultSupportedMetaProps = [
 const mapSchemaTypeToFieldSchema = ({ key = null, value, props, omitFields }) => {
     const swaggerType = mapMongooseTypeToSwaggerType(value);
     const meta = {};
+
+
+
     for (const metaProp of props) {
         if (value && value[metaProp] != null) {
             meta[metaProp] = value[metaProp];
@@ -100,8 +103,18 @@ const mapSchemaTypeToFieldSchema = ({ key = null, value, props, omitFields }) =>
         const arraySchema = Array.isArray(value) ? value[0] : value.type[0];
         const items = mapSchemaTypeToFieldSchema({ value: arraySchema || {}, props, omitFields });
         meta.items = items;
+
+        if(value.ref !== undefined){
+            meta.items.$ref= `#/components/schemas/${value.ref}`
+
+            delete meta.items.type
+        }
     }
     else if (swaggerType === 'object') {
+        if(value.ref !== undefined){
+            meta.$ref= `#/components/schemas/${value.ref}`
+        }
+
         let fields = [];
         if (value && value.constructor && value.constructor.name === 'Schema') {
             fields = getFieldsFromMongooseSchema(value, { props, omitFields });
@@ -123,10 +136,21 @@ const mapSchemaTypeToFieldSchema = ({ key = null, value, props, omitFields }) =>
         meta.properties = properties;
     }
     else if (swaggerType === 'map') {
+        if(value.ref !== undefined){
+            meta.$ref= `#/components/schemas/${value.ref}`
+        }
+
         const subSchema = mapSchemaTypeToFieldSchema({ value: value.of || {}, props, omitFields });
         meta.type = 'object';
         meta.additionalProperties = subSchema;
     }
+    else{
+        if(value.ref !== undefined){
+            meta.$ref= `#/components/schemas/${value.ref}`
+
+            delete meta.type
+        }
+    }
     const result = Object.assign({ type: swaggerType }, meta);
     if (key) {
         result.field = key;

This issue body was partially generated by patch-package.