Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for mongoose validators -min/max and minLength/maxLength #3

Merged
merged 6 commits into from
Aug 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@
"ecmaVersion": "latest"
},
"rules": {
"guard-for-in": "off",
"no-restricted-syntax": "off"
}
}
150 changes: 113 additions & 37 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
const mongoose = require("mongoose");
const { typeToMethodMap, commonFieldsToFakerMap } = require("./lib/mapper");
const { isMongooseSchema } = require("./lib/utils");
/* eslint-disable no-underscore-dangle */
const mongoose = require('mongoose');
const { faker } = require('@faker-js/faker/locale/en');
const { unflatten } = require('flat');
const { typeToMethodMap, commonFieldsToFakerMap } = require('./lib/mapper');
const { isMongooseSchema } = require('./lib/utils');

const { Decimal128 } = mongoose;
const { faker } = require("@faker-js/faker/locale/en");
const unflatten = require("flat").unflatten;

/**
* Handle Array fields - There are two types here
* 1. Array of mongoose primitive data types
* 2. Array of subdocuments with its own schema
* @param {*} schemaField - Field in mongoose schema of type array
* @param {string} fieldName - Name of the array field
* Extract min/max validator values for String & Number schema types
* Min/Max can be a Number or Array
* @param {Number | Array} validator
* @returns
*/
function _mockArrayDataType(schemaField, fieldName) {
if (schemaField.schema) {
return [generateMock(schemaField.schema)];
function _getMinMaxFromSchema(validator) {
if (Array.isArray(validator)) {
return validator[0];
}
const fieldType = schemaField["$embeddedSchemaType"].instance;
return [_getMockValue(fieldName, fieldType)];
return validator;
}

/**
* Get mock value from faker for given field type
* @param {string} fieldName
Expand All @@ -28,14 +28,36 @@ function _mockArrayDataType(schemaField, fieldName) {
function _getMockValue(fieldName, fieldType, fakerOptions = {}) {
let fakerMethod = typeToMethodMap[fieldType];
const commonFields = Object.keys(commonFieldsToFakerMap);
const matchingCommonField = commonFields.find((field) =>
fieldName.toLowerCase().includes(field)
);
const matchingCommonField = commonFields.find((field) => fieldName.toLowerCase().includes(field));
const {
min, max, minLength, maxLength,
} = fakerOptions;

if (fakerOptions.enum && fakerOptions.enumValues) {
// TODO=> Validate if enum values follow min/max validations
return faker.helpers.arrayElement(fakerOptions.enumValues);
}

if (min || max) {
const options = {
...(min && { min }),
...(max && { max }),
};
return faker[fakerMethod.module][fakerMethod.type](options);
}

if (minLength || maxLength) {
const options = {
...(minLength && { min: minLength }),
...(maxLength && { max: maxLength }),
};
/**
* Using different faker module since word.sample will error/return incorrect value
* when it can't find word within given min/max range in its corpus
*/
return faker.string.sample(options);
}

if (matchingCommonField) {
fakerMethod = commonFieldsToFakerMap[matchingCommonField];
return faker[fakerMethod.module][fakerMethod.type]();
Expand All @@ -44,16 +66,18 @@ function _getMockValue(fieldName, fieldType, fakerOptions = {}) {
if (fakerMethod) {
return faker[fakerMethod.module][fakerMethod.type]();
}

return null;
// Fallback/default faker value
return faker.string.sample();
}

/**
* Use mongoose field options like enum, min, max etc to form options to use while
* creating faker object
* @param {object} mongooseField
*/
function _constructFakerOptions(mongooseField) {
const fakerOptions = {};
const mongooseValidators = ['min', 'max', 'minLength', 'maxLength'];
/**
* Using options.enum instead of enumValues at root level of field definition
* since enumValues is not available in case of nested schemas.
Expand All @@ -62,29 +86,48 @@ function _constructFakerOptions(mongooseField) {
fakerOptions.enum = true;
fakerOptions.enumValues = mongooseField.options.enum;
}
if (mongooseField?.options) {
for (const validator of mongooseValidators) {
fakerOptions[validator] = _getMinMaxFromSchema(mongooseField.options[validator]);
}
}

return fakerOptions;
}

/**
* Handle Array fields - There are two types here
* 1. Array of mongoose primitive data types
* 2. Array of subdocuments with its own schema
* @param {*} schemaField - Field in mongoose schema of type array
* @param {string} fieldName - Name of the array field
*/
function _mockArrayDataType(schemaField, fieldName) {
if (schemaField.schema) {
// eslint-disable-next-line no-use-before-define
return [generateMock(schemaField.schema)];
}
const fieldType = schemaField.$embeddedSchemaType.instance;
return [_getMockValue(fieldName, fieldType)];
}
/**
* Create a mock object based on mongoose schema
* @param {*} schema - mongoose schema
* @param {object} options - options from client for mock generation
*/
function generateMock(schema, options = {}) {
function generateMock(schema) {
if (!schema || !isMongooseSchema(schema)) {
throw new Error("Valid mongoose schema is required to generate mock");
throw new Error('Valid mongoose schema is required to generate mock');
}

const mock = {};
for (const fieldName in schema.paths) {
const field = schema.paths[fieldName];
const fieldType = field.instance;

// Handle nested schemas
if (fieldType === "Embedded") {
if (fieldType === 'Embedded') {
mock[fieldName] = generateMock(field.schema);
}
// Handle arrays
else if (fieldType === "Array") {
} else if (fieldType === 'Array') {
mock[fieldName] = _mockArrayDataType(field, fieldName);
} else {
const fakerOptions = _constructFakerOptions(field);
Expand All @@ -101,22 +144,56 @@ const addressSchema = new mongoose.Schema({
zipCode: String,
});

const fiel931Schema = new mongoose.Schema({
field9311: {
type: String,
enum: ['Hey', 'there'],
},
field9312: {
type: Number,
min: 10,
max: 12,
},
field9313: {
type: String,
minLength: 5,
maxLength: 15,
},
});

const field9Schema = new mongoose.Schema({
field91: {
type: Number,
enum: [42, 69, 420],
},
field92: String,
field92: {
type: Number,
min: 1000,
max: 1050,
},
field93: {
field931: String,
field931: fiel931Schema,
},
field94: {
type: String,
minLength: 50,
maxLength: 500,
},
});
const userSchema = new mongoose.Schema({
email: { type: String, required: true },
phoneNumber: String,
firstName: { type: String, required: true },
lastName: String,
age: Number,
lastName: {
type: String,
minLength: 5,
maxLength: 200,
},
age: {
type: Number,
min: [10, 'Become an adult bruh'],
max: 100,
},
birthDate: Date,
isActive: Boolean,
address: addressSchema,
Expand All @@ -139,16 +216,15 @@ const userSchema = new mongoose.Schema({
field6: {
field7: {
type: String,
enum: ["either this", "or that"],
enum: ['either this', 'or that'],
},
field9: field9Schema,
},
},
field3: Number,
},
});
//let mockUserAllFields = generateMock(userSchema);
// console.log(JSON.stringify(mockUserAllFields, null, 2));

const mockUserAllFields = generateMock(userSchema);
console.log(JSON.stringify(mockUserAllFields, null, 2));

module.exports.generateMock = generateMock;
module.exports.generateMock = generateMock;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "index.js",
"scripts": {
"test": "nyc --reporter=text-summary --reporter=html mocha --timeout 15000 test.js",
"lint": "eslint **/*.js"
"lint": "eslint . --ignore-pattern 'node_modules/*'"
},
"author": "",
"license": "ISC",
Expand Down
Loading