adminmate-express-mongoose 1.3.2 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,105 +1,118 @@
1
- const _ = require('lodash');
2
- const fnHelper = require('../helpers/functions');
3
-
4
- module.exports.getAll = async (req, res) => {
5
- const modelName = req.params.model;
6
- const segment = req.query.segment;
7
- const search = (req.query.search || '').trim();
8
- const filters = req.query.filters;
9
- const fieldsToFetch = req.headers['am-model-fields'] || [];
10
- const refFields = req.headers['am-ref-fields'] || {};
11
- const fieldsToSearchIn = req.query.search_in_fields || [];
12
- const page = parseInt(req.query.page || 1);
13
- const nbItemPerPage = 10;
14
- const defaultOrdering = [ ['_id', 'DESC'] ];
15
- const order = req.query.order || null;
16
-
17
- const currentModel = fnHelper.getModelObject(modelName);
18
- if (!currentModel) {
19
- return res.status(403).json({ message: 'Invalid request' });
20
- }
21
-
22
- // Get model properties
23
- const keys = fnHelper.getModelProperties(currentModel);
24
-
25
- // Ordering config
26
- const orderConfig = fnHelper.validateOrderStructure(order) ? order : defaultOrdering;
27
- const orderSafe = fnHelper.getCleanOrderStructure(orderConfig);
28
-
29
- // Construct default fields to fetch
30
- const defaultFieldsToFetch = keys
31
- .filter(key => !key.path.includes('.'))
32
- .map(key => key.path);
33
- const fieldsToFetchSafe = Array.isArray(fieldsToFetch) && fieldsToFetch.length ? fieldsToFetch : defaultFieldsToFetch;
34
-
35
- // Construct default fields to search in (only String type)
36
- const defaultFieldsToSearchIn = keys
37
- .filter(key => ['String'].includes(key.type))
38
- .map(key => key.path);
39
- const fieldsToSearchInSafe = Array.isArray(fieldsToSearchIn) && fieldsToSearchIn.length ? fieldsToSearchIn : defaultFieldsToSearchIn;
40
-
41
- // Build ref fields for the model (for mongoose population purpose)
42
- const fieldsToPopulate = fnHelper.getFieldsToPopulate(keys, fieldsToFetchSafe, refFields);
43
-
44
- const queriesArray = [];
45
-
46
- // Search -----------------------------------------------------------------------------
47
-
48
- if (search) {
49
- const searchQuery = fnHelper.constructSearch(search, fieldsToSearchInSafe, fieldsToPopulate);
50
- queriesArray.push(searchQuery);
51
- }
52
-
53
- // Filters ----------------------------------------------------------------------------
54
-
55
- if (filters) {
56
- const filtersQuery = fnHelper.constructQuery(filters);
57
- if (filtersQuery) {
58
- queriesArray.push(filtersQuery);
1
+ const { intersection } = require('lodash');
2
+
3
+ module.exports = _conf => {
4
+ const fnHelper = require('../helpers/functions')(_conf);
5
+
6
+ const getAll = async (req, res) => {
7
+ const modelName = req.params.model;
8
+ const segment = req.query.segment;
9
+ const search = (req.query.search || '').trim();
10
+ const filters = req.query.filters;
11
+ const fieldsToFetch = req.headers['am-model-fields'] || [];
12
+ const refFields = req.headers['am-ref-fields'] || {};
13
+ const fieldsToSearchIn = req.query.search_in_fields || [];
14
+ const page = parseInt(req.query.page || 1);
15
+ const nbItemPerPage = 10;
16
+ const defaultOrdering = [ ['_id', 'DESC'] ];
17
+ const order = req.query.order || null;
18
+
19
+ const currentModel = fnHelper.getModelObject(modelName);
20
+ if (!currentModel) {
21
+ return res.status(403).json({ message: 'Invalid request' });
59
22
  }
60
- }
61
23
 
62
- // Segments ---------------------------------------------------------------------------
24
+ // Get model properties
25
+ const keys = fnHelper.getModelProperties(currentModel);
26
+
27
+ // Ordering config
28
+ const orderConfig = fnHelper.validateOrderStructure(order) ? order : defaultOrdering;
29
+ const orderSafe = fnHelper.getCleanOrderStructure(orderConfig);
30
+
31
+ // Construct default fields to fetch
32
+ let fieldsToFetchSafe = keys
33
+ .filter(key => !key.path.includes('.'))
34
+ .map(key => key.path);
35
+
36
+ // If we get specific fields to display
37
+ if (Array.isArray(fieldsToFetch) && fieldsToFetch.length > 0) {
38
+ const flatKeys = keys.map(key => key.path);
39
+ const validKeys = intersection(fieldsToFetch, flatKeys);
40
+ if (validKeys.length > 0) {
41
+ fieldsToFetchSafe = validKeys;
42
+ }
43
+ }
44
+
45
+ // Construct default fields to search in (only String type)
46
+ const defaultFieldsToSearchIn = keys
47
+ .filter(key => ['String'].includes(key.type))
48
+ .map(key => key.path);
49
+ const fieldsToSearchInSafe = Array.isArray(fieldsToSearchIn) && fieldsToSearchIn.length ? fieldsToSearchIn : defaultFieldsToSearchIn;
50
+
51
+ // Build ref fields for the model (for mongoose population purpose)
52
+ const fieldsToPopulate = fnHelper.getFieldsToPopulate(keys, fieldsToFetchSafe, refFields);
53
+
54
+ const queriesArray = [];
63
55
 
64
- if (segment && segment.type === 'code' && segment.data) {
65
- const modelSegment = fnHelper.getModelSegment(modelName, segment.data);
66
- if (modelSegment) {
67
- queriesArray.push(modelSegment.query);
56
+ // Search -----------------------------------------------------------------------------
57
+
58
+ if (search) {
59
+ const searchQuery = fnHelper.constructSearch(search, fieldsToSearchInSafe, fieldsToPopulate);
60
+ queriesArray.push(searchQuery);
68
61
  }
69
- }
70
-
71
- const findParams = queriesArray.length ? { $and: queriesArray } : {};
72
-
73
- const data = await currentModel
74
- .find(findParams)
75
- .select(fieldsToFetchSafe)
76
- .populate(fieldsToPopulate)
77
- .sort(orderSafe)
78
- .skip(nbItemPerPage * (page - 1))
79
- .limit(nbItemPerPage)
80
- .lean()
81
- .catch(e => {
82
- res.status(403).json({ message: e.message });
83
- });
84
62
 
85
- if (!data) {
86
- return res.status(403).json();
87
- }
63
+ // Filters ----------------------------------------------------------------------------
88
64
 
89
- const dataCount = await currentModel.countDocuments(findParams);
90
- const nbPage = Math.ceil(dataCount / nbItemPerPage);
65
+ if (filters) {
66
+ const filtersQuery = fnHelper.constructQuery(filters);
67
+ if (filtersQuery) {
68
+ queriesArray.push(filtersQuery);
69
+ }
70
+ }
91
71
 
92
- // Make ref fields appeared as link in the dashboard
93
- const formattedData = data.map(item => {
94
- return fnHelper.refFields(item, fieldsToPopulate);
95
- });
72
+ // Segments ---------------------------------------------------------------------------
96
73
 
97
- res.json({
98
- data: formattedData,
99
- count: dataCount,
100
- pagination: {
101
- current: page,
102
- count: nbPage
74
+ if (segment && segment.type === 'code' && segment.data) {
75
+ const modelSegment = fnHelper.getModelSegment(modelName, segment.data);
76
+ if (modelSegment) {
77
+ queriesArray.push(modelSegment.query);
78
+ }
103
79
  }
104
- });
105
- };
80
+
81
+ const findParams = queriesArray.length ? { $and: queriesArray } : {};
82
+
83
+ const data = await currentModel
84
+ .find(findParams)
85
+ .select(fieldsToFetchSafe)
86
+ .populate(fieldsToPopulate)
87
+ .sort(orderSafe)
88
+ .skip(nbItemPerPage * (page - 1))
89
+ .limit(nbItemPerPage)
90
+ .lean()
91
+ .catch(e => {
92
+ res.status(403).json({ message: e.message });
93
+ });
94
+
95
+ if (!data) {
96
+ return res.status(403).json();
97
+ }
98
+
99
+ const dataCount = await currentModel.countDocuments(findParams);
100
+ const nbPage = Math.ceil(dataCount / nbItemPerPage);
101
+
102
+ // Make ref fields appeared as link in the dashboard
103
+ const formattedData = data.map(item => {
104
+ return fnHelper.refFields(item, fieldsToPopulate);
105
+ });
106
+
107
+ res.json({
108
+ data: formattedData,
109
+ count: dataCount,
110
+ pagination: {
111
+ current: page,
112
+ count: nbPage
113
+ }
114
+ });
115
+ };
116
+
117
+ return getAll;
118
+ };
@@ -1,15 +1,19 @@
1
- const fnHelper = require('../helpers/functions');
1
+ module.exports = _conf => {
2
+ const fnHelper = require('../helpers/functions')(_conf);
2
3
 
3
- module.exports.getIn = async (modelName, ids) => {
4
- const currentModel = fnHelper.getModelObject(modelName);
5
- if (!currentModel) {
6
- return null;
7
- }
4
+ const getIn = async (modelName, ids) => {
5
+ const currentModel = fnHelper.getModelObject(modelName);
6
+ if (!currentModel) {
7
+ return null;
8
+ }
8
9
 
9
- // Get corresponding items
10
- const items = await currentModel
11
- .find({ _id: { $in: ids } })
12
- .lean();
10
+ // Get corresponding items
11
+ const items = await currentModel
12
+ .find({ _id: { $in: ids } })
13
+ .lean();
13
14
 
14
- return items;
15
- };
15
+ return items;
16
+ };
17
+
18
+ return getIn;
19
+ };
@@ -1,40 +1,43 @@
1
- const _ = require('lodash');
2
- const fnHelper = require('../helpers/functions');
3
-
4
- module.exports.getOne = async (req, res) => {
5
- const modelName = req.params.model;
6
- const modelItemId = req.params.id;
7
- const fieldsToFetch = req.headers['am-model-fields'] || [];
8
- const refFields = req.headers['am-ref-fields'] || {};
9
-
10
- const currentModel = fnHelper.getModelObject(modelName);
11
- if (!currentModel) {
12
- return res.status(403).json({ message: 'Invalid request' });
13
- }
14
-
15
- const keys = fnHelper.getModelProperties(currentModel);
16
- const defaultFieldsToFetch = keys.map(key => key.path);
17
- const fieldsToFetchSafe = Array.isArray(fieldsToFetch) && fieldsToFetch.length ? fieldsToFetch : defaultFieldsToFetch;
18
-
19
- // Build ref fields for the model (for mongoose population purpose)
20
- const fieldsToPopulate = fnHelper.getFieldsToPopulate(keys, fieldsToFetchSafe, refFields);
21
-
22
- let data = await currentModel
23
- .findById(modelItemId)
24
- .select(fieldsToFetchSafe)
25
- .populate(fieldsToPopulate)
26
- .lean()
27
- .catch(e => {
28
- res.status(403).json({ message: e.message });
1
+ module.exports = _conf => {
2
+ const fnHelper = require('../helpers/functions')(_conf);
3
+
4
+ const getOne = async (req, res) => {
5
+ const modelName = req.params.model;
6
+ const modelItemId = req.params.id;
7
+ const fieldsToFetch = req.headers['am-model-fields'] || [];
8
+ const refFields = req.headers['am-ref-fields'] || {};
9
+
10
+ const currentModel = fnHelper.getModelObject(modelName);
11
+ if (!currentModel) {
12
+ return res.status(403).json({ message: 'Invalid request' });
13
+ }
14
+
15
+ const keys = fnHelper.getModelProperties(currentModel);
16
+ const defaultFieldsToFetch = keys.map(key => key.path);
17
+ const fieldsToFetchSafe = Array.isArray(fieldsToFetch) && fieldsToFetch.length ? fieldsToFetch : defaultFieldsToFetch;
18
+
19
+ // Build ref fields for the model (for mongoose population purpose)
20
+ const fieldsToPopulate = fnHelper.getFieldsToPopulate(keys, fieldsToFetchSafe, refFields);
21
+
22
+ let data = await currentModel
23
+ .findById(modelItemId)
24
+ .select(fieldsToFetchSafe)
25
+ .populate(fieldsToPopulate)
26
+ .lean()
27
+ .catch(e => {
28
+ res.status(403).json({ message: e.message });
29
+ });
30
+
31
+ if (!data) {
32
+ return res.status(403).json();
33
+ }
34
+
35
+ data = fnHelper.refFields(data, fieldsToPopulate);
36
+
37
+ res.json({
38
+ data
29
39
  });
40
+ };
30
41
 
31
- if (!data) {
32
- return res.status(403).json();
33
- }
34
-
35
- data = fnHelper.refFields(data, fieldsToPopulate);
36
-
37
- res.json({
38
- data
39
- });
40
- };
42
+ return getOne;
43
+ };
@@ -1,53 +1,57 @@
1
- const fnHelper = require('../helpers/functions');
2
-
3
- module.exports.getRefs = async (req, res) => {
4
- const modelName = req.params.model;
5
- const ids = req.query.ids;
6
- const refFields = req.headers['am-ref-fields'] || {};
7
- const nbItemPerPage = 20;
8
-
9
- if (!ids) {
10
- return res.status(403).json({ message: 'Missing parameter ids' });
11
- }
12
-
13
- const fieldsToFetchSafe = refFields[modelName];
14
-
15
- // If no ref fields, return default response
16
- if (!fieldsToFetchSafe) {
17
- return res.json({
18
- data: ids.map(id => ({ value: id, label: id }))
1
+ module.exports = _conf => {
2
+ const fnHelper = require('../helpers/functions')(_conf);
3
+
4
+ const getRefs = async (req, res) => {
5
+ const modelName = req.params.model;
6
+ const ids = req.query.ids;
7
+ const refFields = req.headers['am-ref-fields'] || {};
8
+ const nbItemPerPage = 20;
9
+
10
+ if (!ids) {
11
+ return res.status(403).json({ message: 'Missing parameter ids' });
12
+ }
13
+
14
+ const fieldsToFetchSafe = refFields[modelName];
15
+
16
+ // If no ref fields, return default response
17
+ if (!fieldsToFetchSafe) {
18
+ return res.json({
19
+ data: ids.map(id => ({ value: id, label: id }))
20
+ });
21
+ }
22
+
23
+ const currentModel = fnHelper.getModelObject(modelName);
24
+ if (!currentModel) {
25
+ return res.status(403).json({ message: 'Invalid request' });
26
+ }
27
+
28
+ // Find parameters
29
+ const findParams = { _id: ids };
30
+
31
+ const data = await currentModel
32
+ .find(findParams)
33
+ .select(fieldsToFetchSafe)
34
+ .limit(nbItemPerPage)
35
+ .lean()
36
+ .catch(e => {
37
+ res.status(403).json({ message: e.message });
38
+ });
39
+
40
+ if (!data) {
41
+ return res.status(403).json();
42
+ }
43
+
44
+ // Format the response
45
+ const formattedData = ids.map(_id => {
46
+ const match = data.find(d => d._id.toString() === _id.toString());
47
+ const label = match ? fnHelper.fieldsToValues(fieldsToFetchSafe, match) : _id;
48
+ return { value: _id, label };
19
49
  });
20
- }
21
-
22
- const currentModel = fnHelper.getModelObject(modelName);
23
- if (!currentModel) {
24
- return res.status(403).json({ message: 'Invalid request' });
25
- }
26
-
27
- // Find parameters
28
- const findParams = { _id: ids };
29
-
30
- const data = await currentModel
31
- .find(findParams)
32
- .select(fieldsToFetchSafe)
33
- .limit(nbItemPerPage)
34
- .lean()
35
- .catch(e => {
36
- res.status(403).json({ message: e.message });
50
+
51
+ res.json({
52
+ data: formattedData
37
53
  });
54
+ };
38
55
 
39
- if (!data) {
40
- return res.status(403).json();
41
- }
42
-
43
- // Format the response
44
- const formattedData = ids.map(_id => {
45
- const match = data.find(d => d._id.toString() === _id.toString());
46
- const label = match ? fnHelper.fieldsToValues(fieldsToFetchSafe, match) : _id;
47
- return { value: _id, label };
48
- });
49
-
50
- res.json({
51
- data: formattedData
52
- });
53
- };
56
+ return getRefs;
57
+ };
@@ -1,26 +1,29 @@
1
- const _ = require('lodash');
2
- const fnHelper = require('../helpers/functions');
1
+ module.exports = _conf => {
2
+ const fnHelper = require('../helpers/functions')(_conf);
3
3
 
4
- module.exports.postOne = async (req, res) => {
5
- const modelName = req.params.model;
6
- const data = req.body.data;
4
+ const postOne = async (req, res) => {
5
+ const modelName = req.params.model;
6
+ const data = req.body.data;
7
7
 
8
- const currentModel = fnHelper.getModelObject(modelName);
9
- if (!currentModel) {
10
- return res.status(403).json({ message: 'Invalid request' });
11
- }
8
+ const currentModel = fnHelper.getModelObject(modelName);
9
+ if (!currentModel) {
10
+ return res.status(403).json({ message: 'Invalid request' });
11
+ }
12
12
 
13
- const newItem = new currentModel(data);
14
- const newSavedItem = await newItem.save().catch(e => {
15
- const errorObject = fnHelper.buildError(e, 'An error occured when saving the item');
16
- res.status(403).json(errorObject);
17
- });
18
-
19
- if (newSavedItem) {
20
- res.json({
21
- data: {
22
- id: newSavedItem._id // id and not _id to be generic
23
- }
13
+ const newItem = new currentModel(data);
14
+ const newSavedItem = await newItem.save().catch(e => {
15
+ const errorObject = fnHelper.buildError(e, 'An error occured when saving the item');
16
+ res.status(403).json(errorObject);
24
17
  });
25
- }
26
- };
18
+
19
+ if (newSavedItem) {
20
+ res.json({
21
+ data: {
22
+ id: newSavedItem._id // id and not _id to be generic
23
+ }
24
+ });
25
+ }
26
+ };
27
+
28
+ return postOne;
29
+ };
@@ -1,40 +1,45 @@
1
- const _ = require('lodash');
2
- const fnHelper = require('../helpers/functions');
3
-
4
- module.exports.putOne = async (req, res) => {
5
- const modelName = req.params.model;
6
- const modelItemId = req.params.id;
7
- const data = req.body.data;
8
-
9
- const currentModel = fnHelper.getModelObject(modelName);
10
- if (!currentModel) {
11
- return res.status(403).json({ message: 'Invalid request' });
12
- }
13
-
14
- // const { model, itemEditableKeys } = models[modelName];
15
-
16
- // Only keep authorized keys
17
- // const cleanData = {};
18
- // updatableFields.forEach(updatableField => {
19
- // const fieldValue = _.get(data, updatableField);
20
- // if (fieldValue) {
21
- // _.set(cleanData, updatableField, fieldValue)
22
- // }
23
- // });
24
-
25
- const cleanData = data;
26
-
27
- if (Object.keys(cleanData).length) {
28
- try {
29
- await currentModel.findByIdAndUpdate(modelItemId, cleanData, { runValidators: true });
30
- res.json({ data: cleanData });
1
+ // const _ = require('lodash');
2
+
3
+ module.exports = _conf => {
4
+ const fnHelper = require('../helpers/functions')(_conf);
5
+
6
+ const putOne = async (req, res) => {
7
+ const modelName = req.params.model;
8
+ const modelItemId = req.params.id;
9
+ const data = req.body.data;
10
+
11
+ const currentModel = fnHelper.getModelObject(modelName);
12
+ if (!currentModel) {
13
+ return res.status(403).json({ message: 'Invalid request' });
31
14
  }
32
- catch(e) {
33
- const errorObject = fnHelper.buildError(e, 'Unable to update the model');
34
- res.status(403).json(errorObject);
15
+
16
+ // const { model, itemEditableKeys } = models[modelName];
17
+
18
+ // Only keep authorized keys
19
+ // const cleanData = {};
20
+ // updatableFields.forEach(updatableField => {
21
+ // const fieldValue = _.get(data, updatableField);
22
+ // if (fieldValue) {
23
+ // _.set(cleanData, updatableField, fieldValue)
24
+ // }
25
+ // });
26
+
27
+ const cleanData = data;
28
+
29
+ if (Object.keys(cleanData).length) {
30
+ try {
31
+ await currentModel.findByIdAndUpdate(modelItemId, cleanData, { runValidators: true });
32
+ res.json({ data: cleanData });
33
+ }
34
+ catch(e) {
35
+ const errorObject = fnHelper.buildError(e, 'Unable to update the model');
36
+ res.status(403).json(errorObject);
37
+ }
35
38
  }
36
- }
37
- else {
38
- res.json({});
39
- }
40
- };
39
+ else {
40
+ res.json({});
41
+ }
42
+ };
43
+
44
+ return putOne;
45
+ };