Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
@nodebrick/nodebrick-core
Advanced tools
Core of the Nodebrick framework
This is the core of the framework and works as a glue between all the modules and is required by all application you will create
non exhaustive list
Few things to note:
index.ts
I<ModuleNameModule>.ts
export abstract class I<ModuleName>
to define interface so they exists in the JS realm and are accessible by InversifyJS<ModuleNameModule>.ts
The module class implementing and extending the 'interface'<ModuleNameBindings>.ts
models
Folder storing all our models, i.e our business logic data@Exclude()
export abstract class IAPIResponse<TData>
{
@Expose({name: `request_id`, toClassOnly: true})
@IsOptional()
public abstract requestId?: string;
@Expose({name: `client_request_id`, toPlainOnly: true})
@IsString()
@IsOptional()
public abstract clientRequestId?: string;
@Expose({name: `start_time`, toPlainOnly: true})
@IsDate()
public abstract startTime?: Date;
@Expose({name: `end_time`, toPlainOnly: true})
@IsDate()
public abstract endTime: Date;
@Expose({toPlainOnly: true})
@IsInt()
@IsOptional()
// In milliseconds
public abstract duration?: number;
}
For instance a REST API returning the above will automatically create a JSON like
{
"client_request_id": "933ca46c-25a5-4166-903e-a437700ae4ef",
"startTime": "933ca46c-25a5-4166-903e-a437700ae4ef",
"end_time": "933ca46c-25a5-4166-903e-a437700ae4ef",
"duration": 50
}
I invite you to read the class-transformer and class-validator documentations.NodebrickCore provides dependency injection by using internally InversifyJS
All the bindings will be defined in the <ModuleNameBindings>.ts
as for instance
// bind the module to its interface using transitive binding, i.e we are reusing the singleton.
bind(INodebrickApiModule).toService(NodebrickApiModule);
// middlewares - transient
bind(IGlobalApiMiddleware).to(GlobalApiMiddleware).inTransientScope();
bind(IGlobalOptionsMiddleware).to(GlobalOptionsMiddleware).inTransientScope();
bind(IGlobalRequestMiddleware).to(GlobalRequestMiddleware).inTransientScope();
// services - singletons
bind(INodebrickApiService).to(NodebrickApiService).inSingletonScope();
As you can see bindings can have multiples scopes, Transient, Singleton and Request.
Please see InversifyJS documentation.
A context can be defined as all the relevant information that a developer needs to complete a task.
Nodebrick Core uses cls-hooked internally.
We invite you to read the documentation.
Here is an excerpt of the documentation explaining the core of this library and how it is helping
Continuation-local storage works like thread-local storage in threaded programming, but is based on chains of Node-style callbacks instead of threads. The standard Node convention of functions calling functions is very similar to something called "continuation-passing style" in functional programming, and the name comes from the way this module allows you to set and get values that are scoped to the lifetime of these chains of function calls
When you set values in continuation-local storage, those values are accessible until all functions called from the original function – synchronously or asynchronously – have finished executing. This includes callbacks passed to process.nextTick and the timer functions (setImmediate, setTimeout, and setInterval), as well as callbacks passed to asynchronous functions that call native functions (such as those exported from the fs, dns, zlib and crypto modules).
A simple rule of thumb is anywhere where you want to have threaded scoped variables should now use continuation-local storage. This API is designed to allow you extend the scope of a variable across a sequence of function calls, but with values specific to each sequence of calls. Values are grouped into namespaces, created with createNamespace(). Sets of function calls are grouped together by calling them within the function passed to .run() on the namespace object. Calls to .run() can be nested, and each nested context this creates has its own copy of the set of values from the parent context. When a function is making multiple asynchronous calls, this allows each child call to get, set, and pass along its own context without overwriting the parent's.
This is a diagram explaining the above
And this is the cls-hooked documention explaining it with code
A simple, annotated example of how this nesting behaves:
var createNamespace = require('cls-hooked').createNamespace; var writer = createNamespace('writer'); writer.run(function () { writer.set('value', 0); requestHandler(); }); function requestHandler() { writer.run(function(outer) { // writer.get('value') returns 0 // outer.value is 0 writer.set('value', 1); // writer.get('value') returns 1 // outer.value is 1 process.nextTick(function() { // writer.get('value') returns 1 // outer.value is 1 writer.run(function(inner) { // writer.get('value') returns 1 // outer.value is 1 // inner.value is 1 writer.set('value', 2); // writer.get('value') returns 2 // outer.value is 1 // inner.value is 2 }); }); }); setTimeout(function() { // runs with the default context, because nested contexts have ended console.log(writer.get('value')); // prints 0 }, 1000); }
This also helps segregating the stream of processes (think for instance multiple call to an API, we will create a context when we get a request isolating any models in the context)
Nodebrick Core provides you with tools to:
Please see the following example
abstract class ISomeClass {}
class IATypedValue {
public someProperty: string;
}
abstract class IATypedValueContext extends IContext<IATypedValue> {}
class SomeClass extends ISomeClass implements ISomeClass
{
private readonly _applicationContext: IApplicationContextService;
private readonly _logger: INodebrickLoggerService;
// dependency injection
public constructor(
applicationContext: IApplicationContextService
)
{
super();
this._applicationContext = applicationContext;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async someMethod(): Promise<void>
{
// this creates a new context copying the values from the parent (if any)
this._applicationContext.session.run(() =>
{
// set a value in the context
this._applicationContext.set(IATypedValueContext, {someProperty: "it works"});
});
}
}
abstract class ISomeOtherClass {}
class SomeOtherClass extends ISomeOtherClass implements ISomeOtherClass
{
private readonly _applicationContext: IApplicationContextService;
// dependency injection
public constructor(
applicationContext: IApplicationContextService,
logger: INodebrickLoggerService,
)
{
super();
this._applicationContext = applicationContext;
this._logger = logger;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async someMethod(): Promise<void>
{
// this creates a new context copying the values from the parent (if any)
const aTypedValue: IATypedValue = this._applicationContext.get(IATypedValueContext);
// log "it works"
console.log(aTypedValue.someProperty)
}
}
FAQs
Core of Nodebrick
The npm package @nodebrick/nodebrick-core receives a total of 3 weekly downloads. As such, @nodebrick/nodebrick-core popularity was classified as not popular.
We found that @nodebrick/nodebrick-core demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.