mongodb-dynamic-api
Version:
Auto generated CRUD API for MongoDB using NestJS
86 lines • 3.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DynamicApiGlobalStateService = void 0;
const mongoose_1 = require("mongoose");
const rxjs_1 = require("rxjs");
class DynamicApiGlobalStateService {
constructor(initialGlobalState = {}) {
this.defaultGlobalState = {
uri: '',
connectionName: 'dynamic-api-connection',
isGlobalCacheEnabled: true,
isAuthEnabled: false,
credentials: null,
jwtSecret: undefined,
jwtExpirationTime: undefined,
cacheExcludedPaths: [],
routesConfig: {
excluded: [],
defaults: [
'GetMany',
'GetOne',
'CreateMany',
'CreateOne',
'UpdateMany',
'UpdateOne',
'ReplaceOne',
'DuplicateMany',
'DuplicateOne',
'DeleteMany',
'DeleteOne',
],
},
};
this.resetState(initialGlobalState);
}
static onInitialized() {
return this.initialized$;
}
static addEntitySchema(entity, schema) {
const entitySchemas = this.entitySchemas$.value;
if (entitySchemas[entity.name]) {
return;
}
entitySchemas[entity.name] = schema;
this.entitySchemas$.next(entitySchemas);
}
static async getEntityModel(entity) {
const schema = this.entitySchemas$.value[entity.name];
if (!schema) {
throw new Error(`Entity schema for "${entity.name}" not found`);
}
if (!this.connection) {
this.connection =
await (0, mongoose_1.createConnection)(this._.uri, { retryWrites: true, writeConcern: { w: 'majority' } }).asPromise();
}
return this.connection.model(entity.name, schema);
}
set([target, value]) {
if (target === 'partial') {
Object.assign(DynamicApiGlobalStateService._, value);
}
else {
Object.assign(DynamicApiGlobalStateService._, { [target]: value });
}
this.updateState();
}
get(key) {
return (key ? DynamicApiGlobalStateService._[key] : DynamicApiGlobalStateService._);
}
resetState(initialGlobalState = {}) {
DynamicApiGlobalStateService.entitySchemas$.next({});
DynamicApiGlobalStateService.connection = null;
Object.assign(DynamicApiGlobalStateService._, { ...this.defaultGlobalState }, initialGlobalState);
}
updateState() {
if (DynamicApiGlobalStateService._.initialized && !DynamicApiGlobalStateService.initialized$.value) {
DynamicApiGlobalStateService.initialized$.next(true);
}
}
}
exports.DynamicApiGlobalStateService = DynamicApiGlobalStateService;
DynamicApiGlobalStateService.initialized$ = new rxjs_1.BehaviorSubject(false);
DynamicApiGlobalStateService.entitySchemas$ = new rxjs_1.BehaviorSubject({});
DynamicApiGlobalStateService.connection = null;
DynamicApiGlobalStateService._ = {};
//# sourceMappingURL=dynamic-api-global-state.service.js.map