arrest
Version:
OpenAPI v3 compliant REST framework for Node.js, with support for MongoDB and JSON-Schema
107 lines • 3.48 kB
JavaScript
import { getLogger } from 'debuggo';
import decamelize from 'decamelize';
import _ from 'lodash';
import { MongoClient } from 'mongodb';
import { Resource } from '../resource.js';
import { CreateMongoOperation, PatchMongoOperation, QueryMongoOperation, ReadMongoOperation, RemoveMongoOperation, UpdateMongoOperation, } from './operation/index.js';
const logger = getLogger('arrest');
export class MongoResource extends Resource {
constructor(db, info, routes = MongoResource.defaultRoutes()) {
super(info, routes);
this.info = info;
if (typeof db === 'string') {
this.db = MongoClient.connect(db).then((client) => client.db());
}
else {
this.db = Promise.resolve(db);
}
this.indexesChecked = false;
}
initInfo() {
super.initInfo();
if (typeof this.info.id !== 'string') {
this.info.id = '_id';
}
if (typeof this.info.idIsObjectId !== 'boolean') {
this.info.idIsObjectId = this.info.id === '_id';
}
if (!this.info.collection) {
this.info.collection = decamelize('' + this.info.namePlural, { separator: '_' });
}
}
get schema() {
return true;
}
get requestSchema() {
return this.schema;
}
get responseSchema() {
return this.schema;
}
async checkCollectionIndexes(coll) {
const indexes = this.getIndexes();
if (indexes && indexes.length) {
let currIndexes;
try {
currIndexes = await coll.indexes();
}
catch (e) {
currIndexes = [];
}
for (let i of indexes) {
const props = ['unique', 'sparse', 'min', 'max', 'expireAfterSeconds', 'key'];
let c_i = currIndexes.find((t) => {
return _.isEqual(_.pick(i, props), _.pick(t, props));
});
if (!c_i) {
if (this.info.createIndexes) {
logger.info(this.info.name, 'creating missing index', i);
await coll.createIndex(i.key, _.omit(i, 'key'));
}
else {
logger.warn(this.info.name, 'missing index', i);
}
}
}
}
this.indexesChecked = true;
}
async getCollection(opts = this.getCollectionOptions()) {
let db = await this.db;
let coll = db.collection(this.info.collection, opts);
if (!this.indexesChecked) {
await this.checkCollectionIndexes(coll);
}
return coll;
}
getCollectionOptions() {
return {};
}
getIndexes() {
return this.info.id && this.info.id !== '_id'
? [
{
key: {
[this.info.id]: 1,
},
unique: true,
},
]
: undefined;
}
static defaultRoutes() {
return {
'/': {
get: QueryMongoOperation,
post: CreateMongoOperation,
},
'/:id': {
get: ReadMongoOperation,
put: UpdateMongoOperation,
delete: RemoveMongoOperation,
patch: PatchMongoOperation,
},
};
}
}
//# sourceMappingURL=resource.js.map