mandarinrobotics-nestjs 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc.js ADDED
@@ -0,0 +1,25 @@
1
+ module.exports = {
2
+ parser: '@typescript-eslint/parser',
3
+ parserOptions: {
4
+ project: 'tsconfig.json',
5
+ tsconfigRootDir: __dirname,
6
+ sourceType: 'module',
7
+ },
8
+ plugins: ['@typescript-eslint/eslint-plugin'],
9
+ extends: [
10
+ 'plugin:@typescript-eslint/recommended',
11
+ 'plugin:prettier/recommended',
12
+ ],
13
+ root: true,
14
+ env: {
15
+ node: true,
16
+ jest: true,
17
+ },
18
+ ignorePatterns: ['.eslintrc.js'],
19
+ rules: {
20
+ '@typescript-eslint/interface-name-prefix': 'off',
21
+ '@typescript-eslint/explicit-function-return-type': 'off',
22
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
23
+ '@typescript-eslint/no-explicit-any': 'off',
24
+ },
25
+ };
package/.prettierrc ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "singleQuote": true,
3
+ "trailingComma": "all"
4
+ }
package/README.md ADDED
@@ -0,0 +1,73 @@
1
+ <p align="center">
2
+ <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
3
+ </p>
4
+
5
+ [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
6
+ [circleci-url]: https://circleci.com/gh/nestjs/nest
7
+
8
+ <p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
11
+ <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
12
+ <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
13
+ <a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
14
+ <a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
15
+ <a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
16
+ <a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
17
+ <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
18
+ <a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
19
+ <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
20
+ <a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
21
+ </p>
22
+ <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
23
+ [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
24
+
25
+ ## Description
26
+
27
+ [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
28
+
29
+ ## Installation
30
+
31
+ ```bash
32
+ $ npm install
33
+ ```
34
+
35
+ ## Running the app
36
+
37
+ ```bash
38
+ # development
39
+ $ npm run start
40
+
41
+ # watch mode
42
+ $ npm run start:dev
43
+
44
+ # production mode
45
+ $ npm run start:prod
46
+ ```
47
+
48
+ ## Test
49
+
50
+ ```bash
51
+ # unit tests
52
+ $ npm run test
53
+
54
+ # e2e tests
55
+ $ npm run test:e2e
56
+
57
+ # test coverage
58
+ $ npm run test:cov
59
+ ```
60
+
61
+ ## Support
62
+
63
+ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
64
+
65
+ ## Stay in touch
66
+
67
+ - Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
68
+ - Website - [https://nestjs.com](https://nestjs.com/)
69
+ - Twitter - [@nestframework](https://twitter.com/nestframework)
70
+
71
+ ## License
72
+
73
+ Nest is [MIT licensed](LICENSE).
@@ -0,0 +1,40 @@
1
+ import { CanActivate, ExecutionContext, Injectable, InternalServerErrorException, Logger, UnauthorizedException } from "@nestjs/common";
2
+ import { Request } from "express";
3
+ import { HttpService } from "@nestjs/axios";
4
+
5
+ @Injectable()
6
+ export class AuthGuard implements CanActivate {
7
+ logger = new Logger('AuthGuard');
8
+ authApiURL: string = process.env.AUTH_API;
9
+ httpService = new HttpService();
10
+
11
+ async canActivate(context: ExecutionContext): Promise<boolean> {
12
+ const request = context.switchToHttp().getRequest();
13
+ const token = this.extractTokenFromHeader(request);
14
+
15
+ if (!token) {
16
+ throw new UnauthorizedException();
17
+ }
18
+
19
+ const url = `${this.authApiURL}/validate?accessToken=${token}`;
20
+
21
+ let response: any;
22
+ try {
23
+ response = await this.httpService.axiosRef.get(url);
24
+
25
+ //assign payload to request object
26
+ request['sub'] = response.data.sub;
27
+ this.logger.debug(`Requestor ${response.data.sub}`);
28
+ } catch (error) {
29
+ this.logger.error(error);
30
+ throw new InternalServerErrorException("Validate Token failed");
31
+ }
32
+
33
+ return true;
34
+ }
35
+
36
+ private extractTokenFromHeader(request: Request): string | undefined {
37
+ const [type, token] = request.headers.authorization?.split(' ') ?? [];
38
+ return type === "Bearer" ? token : undefined;
39
+ }
40
+ }
@@ -0,0 +1,11 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { AuthService } from './auth.service';
3
+ import { HttpModule } from '@nestjs/axios';
4
+ import { AuthGuard } from './auth.guard';
5
+
6
+ @Module({
7
+ imports: [HttpModule],
8
+ providers: [AuthService, AuthGuard],
9
+ exports: [AuthService, AuthGuard],
10
+ })
11
+ export class AuthModule { }
@@ -0,0 +1,18 @@
1
+ import { Test, TestingModule } from '@nestjs/testing';
2
+ import { AuthService } from './auth.service';
3
+
4
+ describe('AuthService', () => {
5
+ let service: AuthService;
6
+
7
+ beforeEach(async () => {
8
+ const module: TestingModule = await Test.createTestingModule({
9
+ providers: [AuthService],
10
+ }).compile();
11
+
12
+ service = module.get<AuthService>(AuthService);
13
+ });
14
+
15
+ it('should be defined', () => {
16
+ expect(service).toBeDefined();
17
+ });
18
+ });
@@ -0,0 +1,53 @@
1
+ import { HttpService } from '@nestjs/axios';
2
+ import { Injectable, InternalServerErrorException, Logger, OnModuleInit } from '@nestjs/common';
3
+
4
+ @Injectable()
5
+ export class AuthService implements OnModuleInit {
6
+ private readonly logger = new Logger('AuthService');
7
+ private httpService = new HttpService();
8
+ private systemAccessToken: string;
9
+ private authApiURL = process.env.AUTH_API
10
+
11
+ async onModuleInit() {
12
+ this.systemAccessToken = await this.login();
13
+ this.logger.log(`System logged in via ${this.authApiURL}`);
14
+ this.logger.debug(this.systemAccessToken);
15
+ }
16
+
17
+ private async login() {
18
+ const loginURL = `${this.authApiURL}/login`;
19
+
20
+ let authCode: string;
21
+ try {
22
+ const response = await this.httpService.axiosRef.post(
23
+ loginURL,
24
+ {
25
+ emailAddress: process.env.SYSTEM_LOGIN,
26
+ password: process.env.SYSTEM_PASSWORD
27
+ });
28
+
29
+ authCode = response.data.authCode;
30
+ } catch (error) {
31
+ this.logger.error(error);
32
+ throw new InternalServerErrorException("login API not available");
33
+ }
34
+
35
+ let accessToken: string;
36
+ try {
37
+ const accessURL = `${this.authApiURL}/access?authCode=${authCode}`
38
+ const response = await this.httpService.axiosRef.get(
39
+ accessURL);
40
+
41
+ accessToken = response.data.accessToken;
42
+ } catch (error) {
43
+ this.logger.error(error);
44
+ throw new InternalServerErrorException("access API not available");
45
+ }
46
+
47
+ return accessToken;
48
+ }
49
+
50
+ getAccessToken() {
51
+ return this.systemAccessToken;
52
+ }
53
+ }
@@ -0,0 +1,3 @@
1
+ export * from './auth.module';
2
+ export * from './auth.service';
3
+ export * from './auth.guard';
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "outDir": "../../packages/auth"
6
+ },
7
+ "include": [
8
+ "src/**/*"
9
+ ],
10
+ "exclude": [
11
+ "node_modules",
12
+ "dist",
13
+ "test",
14
+ "**/*spec.ts"
15
+ ]
16
+ }
@@ -0,0 +1,30 @@
1
+ import { Injectable, OnApplicationShutdown } from "@nestjs/common";
2
+ import { Consumer, ConsumerRunConfig, ConsumerSubscribeTopics, Kafka } from "kafkajs";
3
+
4
+ @Injectable()
5
+ export class ConsumerService implements OnApplicationShutdown {
6
+
7
+ private readonly kafka = new Kafka({
8
+ brokers: [process.env.KAFKA_BROKERS]
9
+ })
10
+
11
+ private readonly consumers: Consumer[] = []
12
+
13
+ async consume(topics: ConsumerSubscribeTopics, config: ConsumerRunConfig) {
14
+ const consumer = this.kafka.consumer({ groupId: process.env.KAFKA_CONSUMER_GROUP_ID });
15
+
16
+ await consumer.connect();
17
+
18
+ await consumer.subscribe(topics);
19
+
20
+ await consumer.run(config);
21
+
22
+ this.consumers.push(consumer);
23
+ }
24
+
25
+ async onApplicationShutdown() {
26
+ for (const consumer of this.consumers) {
27
+ consumer.disconnect;
28
+ }
29
+ }
30
+ }
@@ -0,0 +1,3 @@
1
+ export * from './kafka.module';
2
+ export * from './consumer.service';
3
+ export * from './producer.service';
@@ -0,0 +1,9 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { ProducerService } from './producer.service';
3
+ import { ConsumerService } from './consumer.service';
4
+
5
+ @Module({
6
+ providers: [ProducerService, ConsumerService],
7
+ exports: [ProducerService, ConsumerService]
8
+ })
9
+ export class KafkaModule { }
@@ -0,0 +1,24 @@
1
+ import { Injectable, OnApplicationShutdown, OnModuleInit } from "@nestjs/common";
2
+ import { Kafka, Producer, ProducerRecord } from "kafkajs";
3
+
4
+ @Injectable()
5
+ export class ProducerService implements OnModuleInit, OnApplicationShutdown {
6
+ private readonly kafka = new Kafka({
7
+ brokers: [process.env.KAFKA_BROKERS],
8
+ clientId: process.env.KAFKA_CLIENT_ID
9
+ })
10
+
11
+ private readonly producer: Producer = this.kafka.producer();
12
+
13
+ async onModuleInit() {
14
+ await this.producer.connect();
15
+ }
16
+
17
+ async produce(record: ProducerRecord) {
18
+ await this.producer.send(record);
19
+ }
20
+
21
+ async onApplicationShutdown(signal?: string) {
22
+ await this.producer.disconnect();
23
+ }
24
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "outDir": "../../packages/kafka"
6
+ },
7
+ "include": [
8
+ "src/**/*"
9
+ ],
10
+ "exclude": [
11
+ "node_modules",
12
+ "dist",
13
+ "test",
14
+ "**/*spec.ts"
15
+ ]
16
+ }
@@ -0,0 +1,2 @@
1
+ export * from './organizations.module';
2
+ export * from './organizations.service';
@@ -0,0 +1,8 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { OrganizationsService } from './organizations.service';
3
+
4
+ @Module({
5
+ providers: [OrganizationsService],
6
+ exports: [OrganizationsService],
7
+ })
8
+ export class OrganizationsModule {}
@@ -0,0 +1,27 @@
1
+ import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
2
+
3
+ @Injectable()
4
+ export class OrganizationsService implements OnModuleInit {
5
+ private readonly logger = new Logger('OrganizationsService');
6
+ private readonly validOrg: Map<string, string> = new Map();
7
+
8
+ async onModuleInit() {
9
+ this.validOrg.set("31b5f2aa-b648-4a9b-a505-8bf0c2763a83", "CAYO Wellness");
10
+ this.validOrg.set("6498fba8-2df4-41f0-8d42-16378847039e", "Mandarin Robotics");
11
+ }
12
+
13
+ validateOrgId(orgId: string): Promise<boolean> {
14
+ return new Promise(async (resolve, reject) => {
15
+ this.logger.debug(`Validating orgId: ${orgId}`);
16
+
17
+ try {
18
+ if (this.validOrg.has(orgId))
19
+ resolve(true);
20
+ else
21
+ resolve(false);
22
+ } catch (error) {
23
+ reject(error);
24
+ }
25
+ });
26
+ }
27
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "declaration": true,
5
+ "outDir": "../../packages/organizations"
6
+ },
7
+ "include": [
8
+ "src/**/*"
9
+ ],
10
+ "exclude": [
11
+ "node_modules",
12
+ "dist",
13
+ "test",
14
+ "**/*spec.ts"
15
+ ]
16
+ }
package/nest-cli.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/nest-cli",
3
+ "collection": "@nestjs/schematics",
4
+ "sourceRoot": "src",
5
+ "compilerOptions": {
6
+ "deleteOutDir": true,
7
+ "webpack": true
8
+ },
9
+ "projects": {
10
+ "auth": {
11
+ "type": "library",
12
+ "root": "libs/auth",
13
+ "entryFile": "index",
14
+ "sourceRoot": "libs/auth/src",
15
+ "compilerOptions": {
16
+ "tsConfigPath": "libs/auth/tsconfig.lib.json"
17
+ }
18
+ },
19
+ "kafka": {
20
+ "type": "library",
21
+ "root": "libs/kafka",
22
+ "entryFile": "index",
23
+ "sourceRoot": "libs/kafka/src",
24
+ "compilerOptions": {
25
+ "tsConfigPath": "libs/kafka/tsconfig.lib.json"
26
+ }
27
+ },
28
+ "organizations": {
29
+ "type": "library",
30
+ "root": "libs/organizations",
31
+ "entryFile": "index",
32
+ "sourceRoot": "libs/organizations/src",
33
+ "compilerOptions": {
34
+ "tsConfigPath": "libs/organizations/tsconfig.lib.json"
35
+ }
36
+ }
37
+ }
38
+ }
package/package.json ADDED
@@ -0,0 +1,81 @@
1
+ {
2
+ "name": "mandarinrobotics-nestjs",
3
+ "version": "0.0.1",
4
+ "description": "Common Nestjs moudles for Mandarin Robotics",
5
+ "author": "Ken Lai",
6
+ "private": false,
7
+ "license": "UNLICENSED",
8
+ "scripts": {
9
+ "build": "rimraf packages && tsc -p ./libs/auth/tsconfig.lib.json && tsc -p ./libs/kafka/tsconfig.lib.json && tsc -p ./libs/organizations/tsconfig.lib.json",
10
+ "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\" \"libs/**/*.ts\"",
11
+ "start": "nest start",
12
+ "start:dev": "nest start --watch",
13
+ "start:debug": "nest start --debug --watch",
14
+ "start:prod": "node dist/main",
15
+ "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
16
+ "test": "jest",
17
+ "test:watch": "jest --watch",
18
+ "test:cov": "jest --coverage",
19
+ "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
20
+ "test:e2e": "jest --config ./test/jest-e2e.json"
21
+ },
22
+ "dependencies": {
23
+ "@nestjs/axios": "^4.0.1",
24
+ "@nestjs/common": "^11.1.11",
25
+ "@nestjs/core": "^11.1.11",
26
+ "@nestjs/microservices": "^11.1.11",
27
+ "@nestjs/platform-express": "^11.1.11",
28
+ "kafkajs": "^2.2.4",
29
+ "reflect-metadata": "^0.1.13",
30
+ "rxjs": "^7.8.1"
31
+ },
32
+ "devDependencies": {
33
+ "@nestjs/cli": "^11.0.14",
34
+ "@nestjs/schematics": "^10.0.0",
35
+ "@nestjs/testing": "^11.1.11",
36
+ "@types/express": "^4.17.17",
37
+ "@types/jest": "^29.5.2",
38
+ "@types/node": "^20.3.1",
39
+ "@types/supertest": "^2.0.12",
40
+ "@typescript-eslint/eslint-plugin": "^6.0.0",
41
+ "@typescript-eslint/parser": "^6.0.0",
42
+ "eslint": "^8.42.0",
43
+ "eslint-config-prettier": "^9.0.0",
44
+ "eslint-plugin-prettier": "^5.0.0",
45
+ "jest": "^29.5.0",
46
+ "prettier": "^3.0.0",
47
+ "source-map-support": "^0.5.21",
48
+ "supertest": "^6.3.3",
49
+ "ts-jest": "^29.1.0",
50
+ "ts-loader": "^9.4.3",
51
+ "ts-node": "^10.9.1",
52
+ "tsconfig-paths": "^4.2.0",
53
+ "typescript": "^5.1.3"
54
+ },
55
+ "jest": {
56
+ "moduleFileExtensions": [
57
+ "js",
58
+ "json",
59
+ "ts"
60
+ ],
61
+ "rootDir": ".",
62
+ "testRegex": ".*\\.spec\\.ts$",
63
+ "transform": {
64
+ "^.+\\.(t|j)s$": "ts-jest"
65
+ },
66
+ "collectCoverageFrom": [
67
+ "**/*.(t|j)s"
68
+ ],
69
+ "coverageDirectory": "./coverage",
70
+ "testEnvironment": "node",
71
+ "roots": [
72
+ "<rootDir>/src/",
73
+ "<rootDir>/libs/"
74
+ ],
75
+ "moduleNameMapper": {
76
+ "^mandarinrobotics/auth(|/.*)$": "<rootDir>/libs/auth/src/$1",
77
+ "^mandarinrobotics/kafka(|/.*)$": "<rootDir>/libs/kafka/src/$1",
78
+ "^mandarinrobotics/organizations(|/.*)$": "<rootDir>/libs/organizations/src/$1"
79
+ }
80
+ }
81
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
4
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "declaration": true,
5
+ "removeComments": true,
6
+ "emitDecoratorMetadata": true,
7
+ "experimentalDecorators": true,
8
+ "allowSyntheticDefaultImports": true,
9
+ "target": "ES2021",
10
+ "sourceMap": true,
11
+ "outDir": "./dist",
12
+ "baseUrl": "./",
13
+ "incremental": true,
14
+ "skipLibCheck": true,
15
+ "strictNullChecks": false,
16
+ "noImplicitAny": false,
17
+ "strictBindCallApply": false,
18
+ "forceConsistentCasingInFileNames": false,
19
+ "noFallthroughCasesInSwitch": false,
20
+ "paths": {
21
+ "mandarinrobotics/auth": [
22
+ "libs/auth/src"
23
+ ],
24
+ "mandarinrobotics/auth/*": [
25
+ "libs/auth/src/*"
26
+ ],
27
+ "mandarinrobotics/kafka": [
28
+ "libs/kafka/src"
29
+ ],
30
+ "mandarinrobotics/kafka/*": [
31
+ "libs/kafka/src/*"
32
+ ],
33
+ "mandarinrobotics/organizations": [
34
+ "libs/organizations/src"
35
+ ],
36
+ "mandarinrobotics/organizations/*": [
37
+ "libs/organizations/src/*"
38
+ ]
39
+ }
40
+ }
41
+ }