arrest
Version:
OpenAPI v3 compliant REST framework for Node.js, with support for MongoDB and JSON-Schema
88 lines • 2.76 kB
JavaScript
import _ from 'lodash';
import { ObjectId } from 'mongodb';
import { API } from '../../api.js';
import { PipelineOperation } from '../../pipeline.js';
import { addConstraint, toMongoQuery, unescapeMongoObject } from '../util.js';
export class MongoOperation extends PipelineOperation {
constructor(resource, path, method, id) {
super(resource, path, method, id);
this.resource = resource;
}
get collection() {
return this.resource.getCollection(this.getCollectionOptions());
}
get requestSchema() {
return this.resource.requestSchema;
}
get responseSchema() {
return this.resource.responseSchema;
}
getCollectionOptions() {
return undefined;
}
getItemQuery(_id) {
try {
return {
['' + this.resource.info.id]: this.resource.info.idIsObjectId ? new ObjectId(_id) : _id,
};
}
catch (error) {
API.fireError(404, 'not_found');
}
}
parseFields(fields) {
let out = { _metadata: 0 };
if (this.resource.info.id !== '_id') {
out['_id'] = 0;
}
if (fields && fields.length) {
out = _.reduce(fields, (o, i) => {
if (i && i !== '_metadata' && !(i === '_id' && i !== this.resource.info.id)) {
if (i !== '_id' && !out['_id']) {
out['_id'] = 0;
}
delete out['_metadata'];
out[i] = 1;
}
return o;
}, out);
}
return out;
}
getAbilityConstraints(ability) {
const out = {};
if (this.scopes) {
for (let resource in this.scopes) {
for (let action in this.scopes[resource]) {
addConstraint(out, toMongoQuery(ability, resource, action));
}
}
}
return out;
}
async createJob(req, res) {
const job = (await super.createJob(req, res));
job.feat.filter = {
fields: true,
data: false,
};
job.coll = await this.collection;
return job;
}
async prepareQuery(job) {
job = (await super.prepareQuery(job));
if (job.req.ability) {
job.query = addConstraint(job.query, this.getAbilityConstraints(job.req.ability));
}
return job;
}
async redactResult(job) {
if (job.data && typeof job.data === 'object') {
if (this.resource.info.escapeProperties) {
job.data = unescapeMongoObject(job.data);
}
}
return super.redactResult(job);
}
}
//# sourceMappingURL=base.js.map