Initial Commit

master
Amir Hossein Moghiseh 2023-04-19 02:05:19 +04:30
commit 5599eba988
26 changed files with 5503 additions and 0 deletions

25
.eslintrc.js 100644
View File

@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir : __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

35
.gitignore vendored 100644
View File

@ -0,0 +1,35 @@
# compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json

4
.prettierrc 100644
View File

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

73
README.md 100644
View File

@ -0,0 +1,73 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<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>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<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>
<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>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<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>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
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).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

11
nest-cli.json 100644
View File

@ -0,0 +1,11 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
"**/*.proto"
],
"watchAssets": true
}
}

80
package.json 100644
View File

@ -0,0 +1,80 @@
{
"name": "micro-producer",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@grpc/grpc-js": "^1.7.3",
"@grpc/proto-loader": "^0.7.3",
"@nestjs/common": "^9.0.0",
"@nestjs/core": "^9.0.0",
"@nestjs/microservices": "^9.2.0",
"@nestjs/passport": "^9.0.0",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/swagger": "^6.1.3",
"kafkajs": "^2.2.2",
"passport": "^0.6.0",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.2.0"
},
"devDependencies": {
"@nestjs/cli": "^9.0.0",
"@nestjs/schematics": "^9.0.0",
"@nestjs/testing": "^9.0.0",
"@types/express": "^4.17.13",
"@types/jest": "28.1.8",
"@types/node": "^16.0.0",
"@types/passport-local": "^1.0.34",
"@types/supertest": "^2.0.11",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"@typescript-eslint/parser": "^5.0.0",
"eslint": "^8.0.1",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"jest": "28.1.3",
"prettier": "^2.3.2",
"source-map-support": "^0.5.20",
"supertest": "^6.1.3",
"ts-jest": "28.0.8",
"ts-loader": "^9.2.3",
"ts-node": "^10.0.0",
"tsconfig-paths": "4.1.0",
"typescript": "^4.7.4"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

View File

@ -0,0 +1,39 @@
import { Metadata, ServerUnaryCall } from '@grpc/grpc-js';
import { Controller, Get, Param, Post, Body } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';
import { lastValueFrom, map, Observable, Subscription } from 'rxjs';
import { AppService } from './app.service';
import { CreateUserDto } from './dto/user/create-user.dto';
import { FindUserDto, FindUserWithUsernameDto } from './dto/user/find-user.dto';
import { User } from './model/User';
@Controller('users')
export class AppController {
constructor(private readonly appService: AppService) {}
@GrpcMethod('UsersService', 'FindUserById')
getUserById(
data: FindUserDto,
metadata: Metadata,
call: ServerUnaryCall<any, any>,
): Observable<User> {
const user: Observable<User> = this.appService.getUserById(data.userId);
return user;
}
@GrpcMethod('UsersService', 'FindUserByUsername')
getUserByUsername(
data: FindUserWithUsernameDto,
metadata: Metadata,
call: ServerUnaryCall<any, any>,
): Observable<User> {
return this.appService.getUserByUsername(data.username);
}
@GrpcMethod('UsersService', 'CreateUser')
createUser(
data: CreateUserDto,
metadata: Metadata,
call: ServerUnaryCall<any, any>,
): Observable<User> {
return this.appService.createUser(data);
}
}

11
src/app.module.ts 100644
View File

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
@Module({
controllers: [AppController],
providers: [AppService],
exports:[AppService]
})
export class AppModule {}

50
src/app.service.ts 100644
View File

@ -0,0 +1,50 @@
import { Injectable } from '@nestjs/common';
import { Client, ClientKafka, Transport } from '@nestjs/microservices';
import { Observable } from 'rxjs';
import { CreateUserDto } from './dto/user/create-user.dto';
import { FindUserDto, FindUserWithUsernameDto } from './dto/user/find-user.dto';
import { User } from './model/User';
@Injectable()
export class AppService {
@Client({
transport: Transport.KAFKA,
options: {
client: {
clientId: 'mini-producer',
brokers: ['localhost:9092'],
},
consumer: {
groupId: 'consumer', // consumer same as in micro service
},
},
})
client: ClientKafka;
serviceName: string = 'USER';
topics = {
find: `find-${this.serviceName}`,
findUsername: `findUsername-${this.serviceName}`,
create: `create-${this.serviceName}`,
};
async onModuleInit() {
this.client.subscribeToResponseOf(this.topics.find);
this.client.subscribeToResponseOf(this.topics.findUsername);
this.client.subscribeToResponseOf(this.topics.create);
await this.client.connect();
}
getUserById(userId: number): Observable<User> {
let findUserDto: FindUserDto = { userId };
return this.client.send(this.topics.find, findUserDto);
}
getUserByUsername(username:string):Observable<User>{
let findUserWithUsernameDto: FindUserWithUsernameDto = { username };
return this.client.send(this.topics.findUsername, findUserWithUsernameDto);
}
createUser(newUserDto: CreateUserDto): Observable<User> {
return this.client.send(this.topics.create, newUserDto);
}
}

View File

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { AppModule } from 'src/app.module';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';
import {PassportModule} from "@nestjs/passport"
@Module({
imports:[AppModule,PassportModule],
providers: [AuthService,LocalStrategy]
})
export class AuthModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,22 @@
import { Injectable } from '@nestjs/common';
import { AppService } from 'src/app.service';
import { User } from 'src/model/User';
@Injectable()
export class AuthService {
constructor(private appService: AppService) {}
user: User;
validateUser(username: string, pass: string): User {
this.appService
.getUserByUsername(username)
.subscribe((_user) => (this.user = _user));
if (!this.user) {
if (this.user && this.user.password === pass) {
const { password, ...result } = this.user;
return this.user;
}
}
return null;
}
}

View File

@ -0,0 +1,19 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { Strategy } from 'passport-local';
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}

View File

@ -0,0 +1,5 @@
export class Response<T> {
error: boolean;
message: string;
data: T;
}

View File

@ -0,0 +1,9 @@
export class CreateUserDto {
name?: string;
username: string;
email: string;
phone?: string;
website?: string;
company?: any;
message?: string;
}

View File

@ -0,0 +1,7 @@
export class FindUserDto {
userId: number;
}
export class FindUserWithUsernameDto {
username: string;
}

View File

@ -0,0 +1,4 @@
export class LoginUserDto {
username: string;
password: string;
}

23
src/main.ts 100644
View File

@ -0,0 +1,23 @@
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
import { join } from 'path';
import { AppModule } from './app.module';
async function bootstrap() {
const BASE_URL = 'localhost:3060';
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.GRPC,
options: {
url: BASE_URL,
package: 'user',
protoPath: join(__dirname, '../src/proto/user.proto'),
},
},
);
await app.listen();
}
bootstrap();

11
src/model/User.ts 100644
View File

@ -0,0 +1,11 @@
export interface User {
id : number,
name?: string,
username?: string,
email?: string,
phone?: string,
website?: string,
company?: any,
message?:string
password?:string,
}

View File

@ -0,0 +1,46 @@
syntax = "proto3";
package user;
service UsersService {
//R
rpc FindUserById (userById) returns (User) {}
rpc FindUserByUsername (userByUsername) returns (User) {}
//C
rpc CreateUser (createUserDto) returns (User) {}
//Auth
rpc LoginUser (loginUserDto) returns (User) {}
}
message userById {
int32 userId = 1;
}
message userByUsername {
int32 username = 1;
}
message loginUserDto {
string username =1;
string password =2;
}
message createUserDto {
string name =1;
string username=2;
string email=3;
string phone=4 ;
string website=5;
string message= 6;
string password=7;
}
message User {
int32 id = 1;
string name = 2;
string username=3;
string email=4;
string phone=5 ;
string website=6;
string message= 7;
}

View File

@ -0,0 +1,24 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});

View File

@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

21
tsconfig.json 100644
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false
}
}

4920
yarn.lock 100644

File diff suppressed because it is too large Load Diff