-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
48 lines (40 loc) · 1.99 KB
/
Copy pathindex.js
File metadata and controls
48 lines (40 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const fs = require('fs')
const readdir = require('util').promisify(fs.readdir)
const mongoose = require('mongoose')
const jsClassProtoFields = ['length', 'prototype']
const mongooseTypesNames = ['String', 'Number', 'Date', 'Buffer', 'Boolean', 'Mixed', 'Object', 'ObjectId', 'Array', 'Decimal128','Map']
const isClassName = (fieldName, modelValue) => {
return fieldName === 'name' && typeof modelValue === 'string'
}
module.exports = async (opts) => {
const connectionOptions = opts.connectionOptions || {}
await mongoose.connect(opts.connectionUrl, connectionOptions)
const modelDir = opts.modelPath
const files = await readdir(modelDir)
const modelsFiles = files.filter(file => !fs.statSync(`${modelDir}/${file}`).isDirectory())
return modelsFiles.reduce((models, modelFile) => {
const modelName = modelFile.split('.js')[0].replace(/[-_]([a-z])/g, function (g) { return g[1].toUpperCase(); })
const Model = require(`${modelDir}/${modelFile}`)
const instance = new Model()
let attributes = {}, staticMethods = [], instanceMethods = []
Object.getOwnPropertyNames(Model).forEach(fieldName => {
if (jsClassProtoFields.includes(fieldName) || isClassName(fieldName, Model[fieldName])) { return }
const field = Model[fieldName]
if (typeof field === 'function' && !mongooseTypesNames.includes(field.name)) {
staticMethods.push(fieldName)
} else {
attributes[fieldName] = field
}
})
Object.getOwnPropertyNames(Object.getPrototypeOf(instance)).forEach(fieldName => {
if (typeof instance[fieldName] === 'function' && fieldName !== 'constructor') {
instanceMethods.push(fieldName)
}
})
const schema = new mongoose.Schema(attributes, opts.schemaOptions)
staticMethods.forEach(methodName => schema.static(methodName, Model[methodName]))
instanceMethods.forEach(methodName => schema.methods[methodName] = instance[methodName])
models[modelName] = mongoose.model(modelName, schema)
return models
}, {})
}