typenexus
Version:
TypeNexus is a good tool for API encapsulation and management. It provides a clean and lightweight way to package TypeORM functionality, helping you build applications faster while reducing template code redundancy and type conversion work.
90 lines (89 loc) • 2.89 kB
JavaScript
let userContainer;
let userContainerOptions;
/**
* Container to be used by this library for inversion control. If container was not implicitly set then by default
* container simply creates a new instance of the given class.
*/
const defaultContainer = new (class {
instances = [];
get(someClass, paramsConstructor = []) {
let instance = this.instances.find((instance) => instance.type === someClass);
if (!instance) {
instance = { type: someClass, object: new someClass(...paramsConstructor) };
this.instances.push(instance);
}
return instance.object;
}
})();
/**
* Gets the IOC container used by this library.
* @param someClass A class constructor to resolve
* @param action The request/response context that `someClass` is being resolved for
*/
export function getFromContainer(someClass, action, paramsConstructor) {
if (userContainer) {
try {
const instance = userContainer.get(someClass, paramsConstructor || [], action);
if (instance)
return instance;
if (!userContainerOptions || !userContainerOptions.fallback)
return instance;
}
catch (error) {
if (!userContainerOptions || !userContainerOptions.fallbackOnErrors)
throw error;
}
}
return defaultContainer.get(someClass, paramsConstructor || []);
}
/**
* Controller metadata.
*/
export class ControllerMetadata {
actions;
/**
* Indicates object which is used by this controller.
*/
target;
/**
* Base route for all actions registered in this controller.
*/
route;
/**
* Controller type. Can be default or json-typed. Json-typed controllers operate with json requests and responses.
*/
type;
/**
* Indicates if this action uses Authorized decorator.
*/
isAuthorizedUsed;
/**
* Middleware "use"-s applied to a whole controller.
*/
uses;
/**
* Roles set by @Authorized decorator.
*/
authorizedRoles;
constructor(args) {
this.target = args.target;
this.route = args.route;
this.type = args.type;
}
/**
* Gets instance of the controller.
* @param action Details around the request session
*/
getInstance(action, paramsConstructor) {
return getFromContainer(this.target, action, paramsConstructor);
}
/**
* Builds everything controller metadata needs.
* Controller metadata should be used only after its build.
*/
build(responseHandlers) {
const authorizedHandler = responseHandlers.find((handler) => handler.type === 'authorized' && !handler.method);
this.isAuthorizedUsed = !!authorizedHandler;
this.authorizedRoles = [].concat((authorizedHandler && authorizedHandler.value) || []);
}
}