-
Notifications
You must be signed in to change notification settings - Fork 39
/
resource.ts
246 lines (217 loc) · 7.66 KB
/
resource.ts
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import { BaseRecord, BaseResource, flat } from 'adminjs'
import get from 'lodash/get.js'
import mongoose from 'mongoose'
import Property from './property.js'
import { convertFilter } from './utils/convert-filter.js'
import { createCastError } from './utils/create-cast-error.js'
import { createDuplicateError } from './utils/create-duplicate-error.js'
import { createValidationError } from './utils/create-validation-error.js'
import { FindOptions } from './utils/filter.types.js'
import errors from './utils/errors.js'
const { MONGOOSE_CAST_ERROR, MONGOOSE_DUPLICATE_ERROR_CODE, MONGOOSE_VALIDATION_ERROR } = errors
/**
* Adapter for mongoose resource
* @private
*/
class Resource extends BaseResource {
private readonly dbType: string = 'mongodb'
/**
* @typedef {Object} MongooseModel
* @private
* @see https://mongoosejs.com/docs/models.html
*/
public readonly MongooseModel: mongoose.Model<any>
/**
* Initialize the class with the Resource name
* @param {MongooseModel} MongooseModel Class which subclass mongoose.Model
* @memberof Resource
*/
constructor(MongooseModel) {
super(MongooseModel)
this.MongooseModel = MongooseModel
}
static isAdapterFor(MoongooseModel) {
return get(MoongooseModel, 'base.constructor.name') === 'Mongoose'
}
databaseName() {
return this.MongooseModel.db.name
}
databaseType() {
return this.dbType
}
name() {
return this.MongooseModel.modelName
}
id() {
return this.MongooseModel.modelName
}
properties() {
return Object.entries(this.MongooseModel.schema.paths).map(([, path], position) => (
new Property(path, position)
))
}
property(name: string) {
return this.properties().find((property) => property.path() === name) ?? null
}
async count(filters = null) {
if (Object.keys(convertFilter(filters)).length > 0) {
return this.MongooseModel.count(convertFilter(filters))
}
return this.MongooseModel.estimatedDocumentCount()
}
// eslint-disable-next-line default-param-last
async find(filters = {}, { limit = 20, offset = 0, sort = {} }: FindOptions) {
const { direction, sortBy } = sort
const sortingParam = {
[sortBy]: direction,
}
const mongooseObjects = await this.MongooseModel
.find(convertFilter(filters), {}, {
skip: offset, limit, sort: sortingParam,
})
// eslint-disable-next-line max-len
return mongooseObjects.map((mongooseObject) => new BaseRecord(Resource.stringifyId(mongooseObject), this))
}
async findOne(id: string) {
const mongooseObject = await this.MongooseModel.findById(id)
return new BaseRecord(Resource.stringifyId(mongooseObject), this)
}
async findMany(ids: string[]) {
const mongooseObjects = await this.MongooseModel.find(
{ _id: ids },
{},
)
return mongooseObjects.map((mongooseObject) => (
new BaseRecord(Resource.stringifyId(mongooseObject), this)
))
}
build(params) {
return new BaseRecord(Resource.stringifyId(params), this)
}
async create(params) {
const parsedParams = this.parseParams(params)
let mongooseDocument = new this.MongooseModel(parsedParams)
try {
mongooseDocument = await mongooseDocument.save()
} catch (error) {
if (error.name === MONGOOSE_VALIDATION_ERROR) {
throw createValidationError(error)
}
if (error.code === MONGOOSE_DUPLICATE_ERROR_CODE) {
throw createDuplicateError(error, mongooseDocument.toJSON())
}
throw error
}
return Resource.stringifyId(mongooseDocument.toObject())
}
async update(id, params) {
const parsedParams = this.parseParams(params)
const unflattedParams = flat.unflatten(parsedParams)
try {
const mongooseObject = await this.MongooseModel.findOneAndUpdate({
_id: id,
}, {
$set: unflattedParams,
}, {
new: true,
runValidators: true,
context: 'query',
})
return Resource.stringifyId(mongooseObject.toObject())
} catch (error) {
if (error.name === MONGOOSE_VALIDATION_ERROR) {
throw createValidationError(error)
}
if (error.code === MONGOOSE_DUPLICATE_ERROR_CODE) {
throw createDuplicateError(error, unflattedParams)
}
// In update cast errors are not wrapped into a validation errors (as it happens in create).
// that is why we have to have a different way of handling them - check out tests to see
// example error
if (error.name === MONGOOSE_CAST_ERROR) {
throw createCastError(error)
}
throw error
}
}
async delete(id) {
return this.MongooseModel.findOneAndRemove({ _id: id })
}
static stringifyId(mongooseObj) {
// By default Id field is an ObjectID and when we change entire mongoose model to
// raw object it changes _id field not to a string but to an object.
// stringify/parse is a path found here: https://github.com/Automattic/mongoose/issues/2790
// @todo We can somehow speed this up
const strinigified = JSON.stringify(mongooseObj)
return JSON.parse(strinigified)
}
/**
* Check all params against values they hold. In case of wrong value it corrects it.
*
* What it does exactly:
* - changes all empty strings to `null`s for the ObjectID properties.
* - changes all empty strings to [] for array fields
*
* @param {Object} params received from AdminJS form
*
* @return {Object} converted params
*/
parseParams(params) {
const parsedParams = { ...params }
// this function handles ObjectIDs and Arrays recursively
const handleProperty = (prefix = '') => (property) => {
const {
path,
schema,
instance,
} = property
// mongoose doesn't supply us with the same path as we're using in our data
// so we need to improvise
const fullPath = [prefix, path].filter(Boolean).join('.')
const value = parsedParams[fullPath]
// this handles missing ObjectIDs
if (instance === 'ObjectID') {
if (value === '') {
parsedParams[fullPath] = null
} else if (value) {
// this works similar as this.stringifyId
parsedParams[fullPath] = value.toString()
}
}
// this handles empty Arrays or recurse into all properties of a filled Array
if (instance === 'Array') {
if (value === '') {
parsedParams[fullPath] = []
} else if (schema && schema.paths) { // we only want arrays of objects (with sub-paths)
const subProperties = Object.values(schema.paths)
// eslint-disable-next-line no-plusplus, no-constant-condition
for (let i = 0; true; i++) { // loop over every item
const newPrefix = `${fullPath}.${i}`
if (parsedParams[newPrefix] === '') {
// this means we have an empty object here
parsedParams[newPrefix] = {}
} else if (!Object.keys(parsedParams).some((key) => key.startsWith(newPrefix))) {
// we're past the last index of this array
break
} else {
// recurse into the object
subProperties.forEach(handleProperty(newPrefix))
}
}
}
}
// this handles all properties of an object
if (instance === 'Embedded') {
if (parsedParams[fullPath] === '') {
parsedParams[fullPath] = {}
} else {
const subProperties = Object.values(schema.paths)
subProperties.forEach(handleProperty(fullPath))
}
}
}
this.properties().forEach(({ mongoosePath }) => handleProperty()(mongoosePath))
return parsedParams
}
}
export default Resource