Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release/3.0 #45

Merged
merged 15 commits into from
Oct 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 25 additions & 24 deletions .github/workflows/run-tests.workflow.yml
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
name: Run tests

on:
workflow_dispatch:
pull_request:
branches:
- main

concurrency:
cancel-in-progress: true
group: test-${{ github.ref }}

jobs:
run_tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16.x
cache: npm
- run: npm ci --audit=false
- run: npm run lint
- run: npm run test
name: Run tests

on:
workflow_dispatch:
pull_request:
branches:
- main
- release/*

concurrency:
cancel-in-progress: true
group: test-${{ github.ref }}

jobs:
run_tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16.x
cache: npm
- run: npm ci --audit=false
- run: npm run lint
- run: npm run test
30 changes: 15 additions & 15 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
# Contributing to `nestjs-cls`

The contribution guide is a work in progress, your firs contribution can be updating the contribution guide :)

If you have an idea on how to improve the lib, feel free to create an issue. If you see an open issue that you'd like to tackle, read below.

## How too contribute, basically

1. Fork the repo
2. Clone locally and install dependencies `npm i`
3. Create a branch for the feature
4. If you add new features, make sure to also add tests - you can run tests with `npm run test`
5. If you're happy with your contribution, create a pull request from the branch against the upstream repo
6. ??
7. Profit
# Contributing to `nestjs-cls`
The contribution guide is a work in progress, your firs contribution can be updating the contribution guide :)
If you have an idea on how to improve the lib, feel free to create an issue. If you see an open issue that you'd like to tackle, read below.
## How too contribute, basically
1. Fork the repo
2. Clone locally and install dependencies `npm i`
3. Create a branch for the feature
4. If you add new features, make sure to also add tests - you can run tests with `npm run test`
5. If you're happy with your contribution, create a pull request from the branch against the upstream repo
6. ??
7. Profit
303 changes: 213 additions & 90 deletions README.md

Large diffs are not rendered by default.

5,433 changes: 2,889 additions & 2,544 deletions package-lock.json

Large diffs are not rendered by default.

25 changes: 13 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"als",
"AsyncLocalStorage",
"async_hooks",
"request context"
"request context",
"async context"
],
"main": "dist/src/index.js",
"types": "dist/src/index.d.ts",
Expand All @@ -41,16 +42,16 @@
"@nestjs/core": "> 7.0.0 < 10"
},
"devDependencies": {
"@nestjs/apollo": "^10.0.17",
"@nestjs/cli": "^9.0.0",
"@nestjs/common": "^9.0.4",
"@nestjs/core": "^9.0.4",
"@nestjs/graphql": "^10.0.18",
"@nestjs/mercurius": "^10.0.17",
"@nestjs/platform-express": "^9.0.4",
"@nestjs/platform-fastify": "^9.0.4",
"@nestjs/schematics": "^9.0.1",
"@nestjs/testing": "^9.0.4",
"@nestjs/apollo": "^10.1.3",
"@nestjs/cli": "^9.1.4",
"@nestjs/common": "^9.1.2",
"@nestjs/core": "^9.1.2",
"@nestjs/graphql": "^10.1.3",
"@nestjs/mercurius": "^10.1.3",
"@nestjs/platform-express": "^9.1.2",
"@nestjs/platform-fastify": "^9.1.2",
"@nestjs/schematics": "^9.0.3",
"@nestjs/testing": "^9.1.2",
"@types/express": "^4.17.13",
"@types/jest": "^28.1.2",
"@types/node": "^18.0.0",
Expand Down Expand Up @@ -87,7 +88,7 @@
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
"src/**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node",
Expand Down
96 changes: 21 additions & 75 deletions src/lib/cls-service-manager.ts
Original file line number Diff line number Diff line change
@@ -1,75 +1,21 @@
import { ClassProvider, ValueProvider } from '@nestjs/common';
import { CLS_DEFAULT_NAMESPACE } from './cls.constants';
import { ClsService } from './cls.service';
import { AsyncLocalStorage } from 'async_hooks';

/**
* Get ClsService injection token (as a string)
*/
export function getClsServiceToken(): string;
/**
* Get namespaced ClsService injection token (as a string)
* @param namespace name of the namespace
* @deprecated Namespace support will be removed in v3.0
*/
export function getClsServiceToken(namespace: string): string;
export function getClsServiceToken(namespace = CLS_DEFAULT_NAMESPACE) {
return `ClsService-${namespace}`;
}

export class ClsServiceManager {
private static namespaces: Record<
string,
AsyncLocalStorage<any> & { name?: string }
> = {};

private static clsServices: Map<string | typeof ClsService, ClsService> =
new Map([
[
ClsService,
new ClsService(this.resolveNamespace(CLS_DEFAULT_NAMESPACE)),
],
]);

private static resolveNamespace(name: string) {
if (!this.namespaces[name]) {
this.namespaces[name] = new AsyncLocalStorage();
this.namespaces[name].name = name;
}
return this.namespaces[name];
}

static addClsService(name: string = CLS_DEFAULT_NAMESPACE) {
const service = new ClsService(this.resolveNamespace(name));
this.clsServices.set(
getClsServiceToken(name),
new ClsService(this.resolveNamespace(name)),
);
return service;
}

/**
* Retrieve a ClsService outside of Nest's DI.
* @param name namespace name, omit for default
* @returns the ClsService with the given namespace
*/
static getClsService(name?: string) {
const cls = this.clsServices.get(
name ? getClsServiceToken(name) : ClsService,
);
if (!cls)
throw new Error(`ClsService with namespace ${name} does not exist`);
return cls;
}

static getClsServicesAsProviders(): Array<
ClassProvider<ClsService> | ValueProvider<ClsService>
> {
return Array.from(this.clsServices.entries()).map(
([provide, service]) => ({
provide,
useValue: service,
}),
);
}
}
import { globalClsSevice } from './cls-service.globals';
import { ClsStore } from './cls.interfaces';
import { ClsService } from './cls.service';
import { ProxyProviderManager } from './proxy-provider/proxy-provider-manager';

export class ClsServiceManager {
private static clsService = globalClsSevice;

/**
* Retrieve a ClsService outside of Nest's DI.
* @returns the ClsService
*/
static getClsService<T extends ClsStore = ClsStore>(): ClsService<T> {
const cls = this.clsService as ClsService<T>;
return cls;
}

static async resolveProxyProviders() {
return await ProxyProviderManager.resolveProxyProviders();
}
}
5 changes: 5 additions & 0 deletions src/lib/cls-service.globals.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { AsyncLocalStorage } from 'async_hooks';
import { ClsService } from './cls.service';

const als = new AsyncLocalStorage();
export const globalClsSevice = new ClsService(als);
15 changes: 7 additions & 8 deletions src/lib/cls.constants.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
export const CLS_REQ = Symbol('CLS_REQUEST');
export const CLS_RES = Symbol('CLS_RESPONSE');
export const CLS_ID = Symbol('CLS_ID');
export const CLS_DEFAULT_NAMESPACE = 'CLS_DEFAULT_NAMESPACE';
export const CLS_MODULE_OPTIONS = 'ClsModuleOptions';
export const CLS_MIDDLEWARE_OPTIONS = 'ClsMiddlewareOptions';
export const CLS_GUARD_OPTIONS = 'ClsGuardOptions';
export const CLS_INTERCEPTOR_OPTIONS = 'ClsInterceptorOptions';
export const CLS_REQ = Symbol('CLS_REQUEST');
export const CLS_RES = Symbol('CLS_RESPONSE');
export const CLS_ID = Symbol('CLS_ID');
export const CLS_MODULE_OPTIONS = 'ClsModuleOptions';
export const CLS_MIDDLEWARE_OPTIONS = 'ClsMiddlewareOptions';
export const CLS_GUARD_OPTIONS = 'ClsGuardOptions';
export const CLS_INTERCEPTOR_OPTIONS = 'ClsInterceptorOptions';
36 changes: 18 additions & 18 deletions src/lib/cls.decorators.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { Inject } from '@nestjs/common';
import { getClsServiceToken } from './cls-service-manager';
import { CLS_DEFAULT_NAMESPACE } from './cls.constants';

/**
* Use to explicitly inject the ClsService
*/
export function InjectCls(): (target: any, key: string | symbol, index?: number) => void;

/**
* Use to inject a namespaced CLS service
* @param namespace name of the namespace
* @deprecated Namespace support will be removed in v3.0
*/
export function InjectCls(namespace: string): (target: any, key: string | symbol, index?: number) => void;
export function InjectCls(namespace = CLS_DEFAULT_NAMESPACE) {
return Inject(getClsServiceToken(namespace));
}
import { Inject, Injectable, SetMetadata } from '@nestjs/common';
import { ClsService } from './cls.service';
import { CLS_PROXY_METADATA_KEY } from './proxy-provider';
/**
* Use to explicitly inject the ClsService
*/
export function InjectCls() {
return Inject(ClsService);
}
/**
* Mark a Proxy provider with this decorator to distinguis it from regular NestJS singleton providers
*/
export function InjectableProxy() {
return (target: any) =>
Injectable()(SetMetadata(CLS_PROXY_METADATA_KEY, true)(target));
}
69 changes: 35 additions & 34 deletions src/lib/cls.guard.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
} from '@nestjs/common';
import { ClsServiceManager } from './cls-service-manager';
import { CLS_GUARD_OPTIONS, CLS_ID } from './cls.constants';
import { ClsGuardOptions } from './cls.interfaces';

@Injectable()
export class ClsGuard implements CanActivate {
constructor(
@Inject(CLS_GUARD_OPTIONS)
private readonly options?: ClsGuardOptions,
) {
this.options = { ...new ClsGuardOptions(), ...options };
}

async canActivate(context: ExecutionContext): Promise<boolean> {
const cls = ClsServiceManager.getClsService(this.options.namespaceName);
return cls.exit(async () => {
cls.enter();
if (this.options.generateId) {
const id = await this.options.idGenerator(context);
cls.set<any>(CLS_ID, id);
}
if (this.options.setup) {
await this.options.setup(cls, context);
}
return true;
});
}
}
import {
CanActivate,
ExecutionContext,
Inject,
Injectable,
} from '@nestjs/common';
import { ClsServiceManager } from './cls-service-manager';
import { CLS_GUARD_OPTIONS, CLS_ID } from './cls.constants';
import { ClsGuardOptions } from './cls.interfaces';

@Injectable()
export class ClsGuard implements CanActivate {
constructor(
@Inject(CLS_GUARD_OPTIONS)
private readonly options?: ClsGuardOptions,
) {
this.options = { ...new ClsGuardOptions(), ...options };
}

async canActivate(context: ExecutionContext): Promise<boolean> {
const cls = ClsServiceManager.getClsService();
return cls.exit(async () => {
cls.enter();
if (this.options.generateId) {
const id = await this.options.idGenerator(context);
cls.set<any>(CLS_ID, id);
}
if (this.options.setup) {
await this.options.setup(cls, context);
}
await ClsServiceManager.resolveProxyProviders();
return true;
});
}
}
Loading