This repository has been archived by the owner on Jan 12, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
crud.js
92 lines (71 loc) · 1.92 KB
/
crud.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*!
* Crud
* Copyright (c) Henrik Kjelsberg 2012 <henrik@kjelsberg.net>
* MIT licensed
*/
/**
* Module dependencies
*/
var mongoose = require('mongoose')
, cycle = require('cycle')
/**
* Form
*
* Normalizes a mongoose Schema to be used with a form-template
* @param {Mixed} model Model or name of a model
* @param {Function} cb Callback
*/
var form = exports.form = function (model, cb) {
var err
, Model
, Schema
/**
* Retrieve model from mongoose
*/
try {
Model = typeof model === 'string' ? mongoose.model(model) : model
Schema = cycle.decycle(Model.prototype._schema.paths)
}
/**
* Incorrect modelname or faulty model
*/
catch (err) {
return cb(err)
}
/**
* Process Schema
*
* Normalization of the Schema-model to a more humanfriendly JSON format
*/
for (var field in Schema) {
var fieldtype = field.match(/(number|date|email|password|url|tlf)/gi)
// Required
Schema[field]['required'] = typeof Schema[field]['isRequired'] !== 'undefined'
? Schema[field]['isRequired']
: null
// Field type
// TODO #crud Add number, date etc
fieldtype = fieldtype || 'text'
Schema[field]['type'] = typeof Schema[field]['options']['override'] !== 'undefined'
? Schema[field]['options']['override']
: fieldtype
// Field name
Schema[field]['name'] = field.substring(field.lastIndexOf('.') + 1)
for (var prop in Schema[field]) {
if (prop === 'selected' && !field[prop]) delete Schema[field]
}
}
}
/**
* Crud express-middleware
*
* A middleware route for express that populates res.form with the fields from
* the specified model.
*/
exports.middleware = function (req, res, next, model) {
form(model, function (err, form) {
if (err) return next(err)
req.locals('form', form)
return next()
})
}