This repository has been archived by the owner on Jan 12, 2021. It is now read-only.
/
crud.js
125 lines (100 loc) · 2.69 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*!
* 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 = false
, form = {}
, Model
, Schema
, copy = {
'isRequired': 'required'
}
/**
* 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) {
/**
* Ignored fields
*/
for (var prop in Schema[field]) {
if (prop === 'selected' && !field[prop]) continue
}
form[field] = {}
/**
* Copy a bunch of parameters
*
* The value from the copy-object is used as the key to our new form-object
* TODO Need a smarter way of pushing values from Schema to form
*/
for (var key in copy) {
if (typeof Schema[field][key] !== 'undefined') {
form[field][copy[key]] = Schema[field][key]
}
}
/**
* Field name
*/
form[field]['name'] = field.substring(field.lastIndexOf('.') + 1)
/**
* Field type
*/
var fieldtype = field.match(/(number|date|email|password|url|tlf)/gi) || 'text'
form[field]['type'] = Schema[field].instance === 'boolean' ? 'checkbox' : fieldtype
form[field]['type'] = typeof Schema[field]['options']['override'] !== 'undefined'
? Schema[field]['options']['override']
: fieldtype
form[field]['type'] = field[0] === '_' ? 'hidden' : fieldtype
if (typeof Schema[field]['options']['min'] !== 'undefined'
&& Schema[field]['options']['min'] >= 50) {
form[field]['type'] = 'textarea'
}
if (typeof Schema[field]['options']['max'] !== 'undefined') {
form[field]['max'] = Schema[field]['options']['max']
}
console.dir(Schema[field])
}
return cb(err, form)
}
/**
* 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) {
var model = req.params.model
form(model, function (err, form) {
if (err) return next(err)
res.locals({form: form, model: model})
return next()
})
}