init notification
This commit is contained in:
@@ -1 +0,0 @@
|
|||||||
port=3020
|
|
||||||
24
.eslintrc.js
Normal file
24
.eslintrc.js
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
module.exports = {
|
||||||
|
parser: "@typescript-eslint/parser",
|
||||||
|
parserOptions: {
|
||||||
|
project: "tsconfig.json",
|
||||||
|
tsconfigRootDir: __dirname,
|
||||||
|
sourceType: "module",
|
||||||
|
},
|
||||||
|
plugins: ["@typescript-eslint/eslint-plugin"],
|
||||||
|
extends: [
|
||||||
|
"plugin:@typescript-eslint/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",
|
||||||
|
},
|
||||||
|
};
|
||||||
37
.gitignore
vendored
37
.gitignore
vendored
@@ -1,4 +1,35 @@
|
|||||||
|
# compiled output
|
||||||
|
/dist
|
||||||
/node_modules
|
/node_modules
|
||||||
index.js
|
|
||||||
.env
|
# Logs
|
||||||
package-lock.json
|
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
Normal file
4
.prettierrc
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"singleQuote": false,
|
||||||
|
"trailingComma": "all"
|
||||||
|
}
|
||||||
73
README.md
Normal file
73
README.md
Normal 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>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](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).
|
||||||
122
index.ts
122
index.ts
@@ -1,122 +0,0 @@
|
|||||||
import express, { Request, Response, NextFunction } from 'express';
|
|
||||||
import http from 'http'; // Import Node's built-in HTTP module
|
|
||||||
import { Server as SocketServer } from 'socket.io'; // Import Socket.io
|
|
||||||
import { query, body, validationResult } from 'express-validator';
|
|
||||||
import bodyParser from 'body-parser';
|
|
||||||
import { log } from 'console';
|
|
||||||
|
|
||||||
require('dotenv').config();
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
|
|
||||||
const server = http.createServer(app); // Create an HTTP server
|
|
||||||
const io = new SocketServer(server); // Create a Socket.io server instance
|
|
||||||
|
|
||||||
// app.use(bodyParser.urlencoded());
|
|
||||||
|
|
||||||
// app.use(bodyParser.json());
|
|
||||||
|
|
||||||
app.use(express.json());
|
|
||||||
app.use(express.urlencoded({ extended: true }));
|
|
||||||
|
|
||||||
app.post('/test', bodyParser.json(), (req: Request, res: Response) => {
|
|
||||||
console.log(req.body);
|
|
||||||
res.send(req.body);
|
|
||||||
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
const validate = (req: Request, res: Response, next: NextFunction) => {
|
|
||||||
// console.log(req.body);
|
|
||||||
// console.log(JSON.stringify(req.body, null, 2));
|
|
||||||
|
|
||||||
|
|
||||||
const errors = validationResult(req);
|
|
||||||
|
|
||||||
if (!errors.isEmpty()) {
|
|
||||||
return res.status(400).json({ errors: errors.array() });
|
|
||||||
}
|
|
||||||
next();
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
var rules = [
|
|
||||||
body('phone_number').notEmpty(),
|
|
||||||
body('telephone_id').notEmpty(),
|
|
||||||
body('phone_number').isLength({ min: 11, max: 11 }).withMessage("شماره تلفن باید 11 رقم باشد.")
|
|
||||||
];
|
|
||||||
|
|
||||||
|
|
||||||
app.post('/send_notification', rules, validate, (req: Request, res: Response) => {
|
|
||||||
|
|
||||||
|
|
||||||
// console.log(req.body.telephone_id);
|
|
||||||
|
|
||||||
|
|
||||||
io.fetchSockets().then((sockets) => {
|
|
||||||
let find = 0;
|
|
||||||
sockets.map((socket) => {
|
|
||||||
|
|
||||||
if (socket.handshake.auth.token === req.body.telephone_id) {
|
|
||||||
find = 1;
|
|
||||||
socket.timeout(2000).emit("answer", req.body.phone_number, (err: any, responses: Response) => {
|
|
||||||
if (err) {
|
|
||||||
console.log("#2");
|
|
||||||
|
|
||||||
console.log(err);
|
|
||||||
|
|
||||||
res.end("user does not ack");
|
|
||||||
|
|
||||||
// some clients did not acknowledge the event in the given delay
|
|
||||||
} else {
|
|
||||||
console.log("#1");
|
|
||||||
|
|
||||||
console.log(responses); // one response per client
|
|
||||||
res.end("user received notification");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
// res.end("inja");
|
|
||||||
// try {
|
|
||||||
// const responses = socket.timeout(2000).emitWithAck("answer");
|
|
||||||
// res.send(responses); // one response per client
|
|
||||||
// } catch (e) {
|
|
||||||
// res.end("ridim");
|
|
||||||
|
|
||||||
// // some clients did not acknowledge the event in the given delay
|
|
||||||
// }
|
|
||||||
|
|
||||||
// socket.timeout(10000).emitWithAck('new_answer', req.body.phone_number);
|
|
||||||
|
|
||||||
})
|
|
||||||
if (!find) {
|
|
||||||
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
res.end("your message is received ")
|
|
||||||
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
io.on('connection', (socket) => {
|
|
||||||
|
|
||||||
if (socket.recovered) {
|
|
||||||
console.log(socket.handshake.auth.token+':recovered');
|
|
||||||
|
|
||||||
} else {
|
|
||||||
console.log(socket.handshake.auth.token+":connect");
|
|
||||||
}
|
|
||||||
|
|
||||||
socket.on("disconnect", (reason) => {
|
|
||||||
console.log(socket.handshake.auth.token+":"+reason);
|
|
||||||
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
|
|
||||||
// Start the HTTP server
|
|
||||||
server.listen(process.env.port, () => {
|
|
||||||
console.log(`Server is running on port ${process.env.port}`);
|
|
||||||
});
|
|
||||||
8
nest-cli.json
Normal file
8
nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
9041
package-lock.json
generated
9041
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
94
package.json
94
package.json
@@ -1,33 +1,79 @@
|
|||||||
{
|
{
|
||||||
"name": "notificationserver",
|
"name": "notification-server",
|
||||||
"version": "1.0.0",
|
"version": "0.0.1",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
|
||||||
"scripts": {
|
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
|
||||||
"build": "npx tsc",
|
|
||||||
"start": "node index.js",
|
|
||||||
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q index.js\""
|
|
||||||
},
|
|
||||||
"keywords": [],
|
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"scripts": {
|
||||||
|
"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": {
|
"dependencies": {
|
||||||
"@types/socket.io": "^3.0.2",
|
"@nestjs/common": "^10.0.0",
|
||||||
"body-parser": "^1.20.2",
|
"@nestjs/core": "^10.0.0",
|
||||||
"dotenv": "^16.3.1",
|
"@nestjs/platform-express": "^10.0.0",
|
||||||
"express": "^4.18.2",
|
"@nestjs/platform-socket.io": "^10.2.7",
|
||||||
"express-validator": "^7.0.1",
|
"@nestjs/sequelize": "^10.0.0",
|
||||||
"socket.io": "^4.7.2",
|
"@nestjs/websockets": "^10.2.7",
|
||||||
"swagger-jsdoc": "^6.2.8",
|
"class-transformer": "^0.5.1",
|
||||||
"swagger-ui-express": "^5.0.0"
|
"class-validator": "^0.14.0",
|
||||||
|
"mysql2": "^3.6.2",
|
||||||
|
"reflect-metadata": "^0.1.13",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"sequelize": "^6.33.0",
|
||||||
|
"sequelize-typescript": "^2.1.5",
|
||||||
|
"socket.io": "^4.7.2"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@nestjs/cli": "^10.0.0",
|
||||||
|
"@nestjs/schematics": "^10.0.0",
|
||||||
|
"@nestjs/testing": "^10.0.0",
|
||||||
"@types/express": "^4.17.17",
|
"@types/express": "^4.17.17",
|
||||||
"@types/node": "^20.6.2",
|
"@types/jest": "^29.5.2",
|
||||||
"@types/swagger-ui-express": "^4.1.4",
|
"@types/node": "^20.3.1",
|
||||||
"concurrently": "^8.2.1",
|
"@types/sequelize": "^4.28.17",
|
||||||
"nodemon": "^3.0.1",
|
"@types/supertest": "^2.0.12",
|
||||||
"typescript": "^5.2.2"
|
"@typescript-eslint/eslint-plugin": "^6.0.0",
|
||||||
|
"@typescript-eslint/parser": "^6.0.0",
|
||||||
|
"eslint": "^8.42.0",
|
||||||
|
"eslint-config-prettier": "^9.0.0",
|
||||||
|
"eslint-plugin-prettier": "^5.0.0",
|
||||||
|
"jest": "^29.5.0",
|
||||||
|
"prettier": "^3.0.0",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^6.3.3",
|
||||||
|
"ts-jest": "^29.1.0",
|
||||||
|
"ts-loader": "^9.4.3",
|
||||||
|
"ts-node": "^10.9.1",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.1.3"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.defaultRoute = void 0;
|
|
||||||
const express_1 = require("express");
|
|
||||||
exports.defaultRoute = (0, express_1.Router)();
|
|
||||||
exports.defaultRoute.get('/', (req, res) => {
|
|
||||||
res.send("What's up doc ?!");
|
|
||||||
});
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { Router } from 'express';
|
|
||||||
|
|
||||||
export const defaultRoute = Router();
|
|
||||||
|
|
||||||
defaultRoute.get('/', (req, res) => {
|
|
||||||
res.send("What's up doc ?!");
|
|
||||||
});
|
|
||||||
8
routs.js
8
routs.js
@@ -1,8 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
Object.defineProperty(exports, "__esModule", { value: true });
|
|
||||||
exports.defaultRoute = void 0;
|
|
||||||
const express_1 = require("express");
|
|
||||||
exports.defaultRoute = (0, express_1.Router)();
|
|
||||||
exports.defaultRoute.get('/', (req, res) => {
|
|
||||||
res.send("What's up doc ?!");
|
|
||||||
});
|
|
||||||
21
src/app.module.ts
Normal file
21
src/app.module.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
import { NotificationModule } from "./notifications/notification.mudule";
|
||||||
|
import { SequelizeModule } from "@nestjs/sequelize";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
SequelizeModule.forRoot({
|
||||||
|
dialect: "mysql",
|
||||||
|
host: "localhost",
|
||||||
|
port: 3306,
|
||||||
|
username: "root",
|
||||||
|
password: "",
|
||||||
|
database: "notification_db",
|
||||||
|
autoLoadModels: true,
|
||||||
|
synchronize: true,
|
||||||
|
}),
|
||||||
|
NotificationModule,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class AppModule {
|
||||||
|
}
|
||||||
13
src/main.ts
Normal file
13
src/main.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { NestFactory } from "@nestjs/core";
|
||||||
|
import { AppModule } from "./app.module";
|
||||||
|
import { ValidationPipe } from "@nestjs/common";
|
||||||
|
import { IoAdapter } from "@nestjs/platform-socket.io";
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
const app = await NestFactory.create(AppModule);
|
||||||
|
app.useGlobalPipes(new ValidationPipe());
|
||||||
|
app.useWebSocketAdapter(new IoAdapter(app));
|
||||||
|
await app.listen(3001);
|
||||||
|
}
|
||||||
|
|
||||||
|
bootstrap();
|
||||||
5
src/notifications/interfaces/notification.interface.ts
Normal file
5
src/notifications/interfaces/notification.interface.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
export class NotificationInterface {
|
||||||
|
call_id: number;
|
||||||
|
telephone_id: string;
|
||||||
|
phone_number: string;
|
||||||
|
}
|
||||||
18
src/notifications/notification.controller.ts
Normal file
18
src/notifications/notification.controller.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { Body, Controller, Post } from "@nestjs/common";
|
||||||
|
import { NotificationService } from "./notification.service";
|
||||||
|
import { SendNotificationDto } from "./validations/sendNotification.dto";
|
||||||
|
import { SocketGateway } from "../socket/socket.gateway";
|
||||||
|
|
||||||
|
@Controller("notifications")
|
||||||
|
export class NotificationController {
|
||||||
|
constructor(
|
||||||
|
private readonly notificationService: NotificationService,
|
||||||
|
private socketGateway: SocketGateway,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("send")
|
||||||
|
async sendNotification(@Body() notificationData: SendNotificationDto) {
|
||||||
|
return await this.socketGateway.handleSendNotification(notificationData);
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/notifications/notification.mudule.ts
Normal file
15
src/notifications/notification.mudule.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
import { NotificationController } from "./notification.controller";
|
||||||
|
import { NotificationService } from "./notification.service";
|
||||||
|
import { SocketGateway } from "../socket/socket.gateway";
|
||||||
|
import { SocketService } from "../socket/socket.service";
|
||||||
|
import { SequelizeModule } from "@nestjs/sequelize";
|
||||||
|
import { SocketModel } from "../socket/models/socket.model";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [SequelizeModule.forFeature([SocketModel])],
|
||||||
|
controllers: [NotificationController],
|
||||||
|
providers: [NotificationService, SocketGateway, SocketService],
|
||||||
|
})
|
||||||
|
export class NotificationModule {
|
||||||
|
}
|
||||||
5
src/notifications/notification.service.ts
Normal file
5
src/notifications/notification.service.ts
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class NotificationService {
|
||||||
|
}
|
||||||
15
src/notifications/validations/sendNotification.dto.ts
Normal file
15
src/notifications/validations/sendNotification.dto.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { IsInt, IsNotEmpty, IsString } from "class-validator";
|
||||||
|
|
||||||
|
export class SendNotificationDto {
|
||||||
|
@IsNotEmpty()
|
||||||
|
@IsInt()
|
||||||
|
call_id: number;
|
||||||
|
|
||||||
|
@IsNotEmpty()
|
||||||
|
@IsString()
|
||||||
|
telephone_id: string;
|
||||||
|
|
||||||
|
@IsNotEmpty()
|
||||||
|
@IsString()
|
||||||
|
phone_number: string;
|
||||||
|
}
|
||||||
24
src/socket/models/socket.model.ts
Normal file
24
src/socket/models/socket.model.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { Column, DataType, Model, Table } from "sequelize-typescript";
|
||||||
|
|
||||||
|
@Table({ updatedAt: false, tableName: "notifications" })
|
||||||
|
export class SocketModel extends Model {
|
||||||
|
@Column({
|
||||||
|
type: DataType.BIGINT,
|
||||||
|
allowNull: false,
|
||||||
|
autoIncrement: true,
|
||||||
|
primaryKey: true,
|
||||||
|
})
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Column({ allowNull: false })
|
||||||
|
client_id: string;
|
||||||
|
|
||||||
|
@Column({ allowNull: false })
|
||||||
|
socket_id: string;
|
||||||
|
|
||||||
|
@Column({ allowNull: false })
|
||||||
|
event: string;
|
||||||
|
|
||||||
|
@Column
|
||||||
|
description: string;
|
||||||
|
}
|
||||||
61
src/socket/socket.gateway.ts
Normal file
61
src/socket/socket.gateway.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import { OnGatewayConnection, SubscribeMessage, WebSocketGateway, WebSocketServer } from "@nestjs/websockets";
|
||||||
|
import { Server, Socket } from "socket.io";
|
||||||
|
import { NotificationInterface } from "../notifications/interfaces/notification.interface";
|
||||||
|
import { SocketService } from "./socket.service";
|
||||||
|
|
||||||
|
@WebSocketGateway()
|
||||||
|
export class SocketGateway implements OnGatewayConnection {
|
||||||
|
@WebSocketServer() server: Server;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private socketService: SocketService,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
handleConnection(client: Socket) {
|
||||||
|
this.socketService.ClientConnection({
|
||||||
|
client_id: client.handshake.auth.token,
|
||||||
|
socket_id: client.id,
|
||||||
|
event: "connected",
|
||||||
|
});
|
||||||
|
client.on("disconnect", (reason) => {
|
||||||
|
this.socketService.ClientConnection({
|
||||||
|
client_id: client.handshake.auth.token,
|
||||||
|
socket_id: client.id,
|
||||||
|
event: "disconnected",
|
||||||
|
description: reason,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage("sendNotificationToClients")
|
||||||
|
handleSendNotification(notificationData: NotificationInterface) {
|
||||||
|
return new Promise(async (resolve) => {
|
||||||
|
const connectedClients = this.server.sockets.sockets;
|
||||||
|
|
||||||
|
if (connectedClients.size === 0) resolve({ status: "failed", message: "Clients not found!" });
|
||||||
|
|
||||||
|
let sent: any = false;
|
||||||
|
|
||||||
|
for (const connectedClient of connectedClients) {
|
||||||
|
if (connectedClient[1].handshake.auth.token == notificationData.telephone_id) {
|
||||||
|
sent = await new Promise((resolve) => {
|
||||||
|
connectedClient[1].timeout(2000).emit("answer", JSON.stringify(notificationData), (err: any) => {
|
||||||
|
if (err) {
|
||||||
|
resolve(false);
|
||||||
|
} else {
|
||||||
|
resolve(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sent) {
|
||||||
|
resolve({ status: "success", message: "Sent to clients" });
|
||||||
|
} else {
|
||||||
|
resolve({ status: "failed", message: "Not sent to clients" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
16
src/socket/socket.service.ts
Normal file
16
src/socket/socket.service.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { InjectModel } from "@nestjs/sequelize";
|
||||||
|
import { SocketModel } from "./models/socket.model";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SocketService {
|
||||||
|
constructor(
|
||||||
|
@InjectModel(SocketModel)
|
||||||
|
private socketModel: typeof SocketModel,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
ClientConnection(data) {
|
||||||
|
this.socketModel.create(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
92
temp
92
temp
@@ -1,92 +0,0 @@
|
|||||||
import express, { Request, Response } from 'express';
|
|
||||||
import http from 'http'; // Import Node's built-in HTTP module
|
|
||||||
import { Server as SocketServer } from 'socket.io'; // Import Socket.io
|
|
||||||
// import path from 'path';
|
|
||||||
// import dotenv from 'dotenv';
|
|
||||||
require('dotenv').config();
|
|
||||||
// import { env } from 'node:process';
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// import dotenv from 'dotenv';
|
|
||||||
// import { defaultRoute } from './routes';
|
|
||||||
|
|
||||||
// import http from 'http';
|
|
||||||
// import { Server as SocketServer } from 'socket.io';
|
|
||||||
|
|
||||||
|
|
||||||
// dotenv.config();
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const server = http.createServer(app); // Create an HTTP server
|
|
||||||
const io = new SocketServer(server); // Create a Socket.io server instance
|
|
||||||
|
|
||||||
// // Serve static files (optional)
|
|
||||||
// app.use(express.static(path.join(__dirname, 'public')));
|
|
||||||
|
|
||||||
// Middleware to parse JSON
|
|
||||||
app.use(express.json());
|
|
||||||
|
|
||||||
// // Sample data
|
|
||||||
// const users: { id: number; name: string }[] = [
|
|
||||||
// { id: 1, name: 'Alice' },
|
|
||||||
// { id: 2, name: 'Bob' },
|
|
||||||
// ];
|
|
||||||
|
|
||||||
// // Define a route to get all users
|
|
||||||
// app.get('/users', (req: Request, res: Response) => {
|
|
||||||
// res.json(users);
|
|
||||||
// });
|
|
||||||
|
|
||||||
|
|
||||||
app.get('/send_notification', (req: Request, res: Response) => {
|
|
||||||
// io.on('connection', (socket) => {
|
|
||||||
// console.log('A user connected get');
|
|
||||||
console.log(req);
|
|
||||||
res.json([])
|
|
||||||
// io.timeout(2000).emit("message", "fuck this", (err: any, responses: Response) => {
|
|
||||||
// if (err) {
|
|
||||||
// console.log("#2");
|
|
||||||
|
|
||||||
// console.log(err);
|
|
||||||
|
|
||||||
// // some clients did not acknowledge the event in the given delay
|
|
||||||
// } else {
|
|
||||||
// console.log("#1");
|
|
||||||
|
|
||||||
// console.log(responses); // one response per client
|
|
||||||
// }
|
|
||||||
// });
|
|
||||||
// })
|
|
||||||
// res.json(users);
|
|
||||||
});
|
|
||||||
|
|
||||||
// ... (Previous route definitions)
|
|
||||||
|
|
||||||
// Socket.io setup
|
|
||||||
io.on('connection', (socket) => {
|
|
||||||
// console.log(socket.handshake.auth.token);
|
|
||||||
|
|
||||||
// console.log('A user connected');
|
|
||||||
|
|
||||||
// Example: Send a message to the connected client
|
|
||||||
// socket.emit('message', 'Welcome to the chat!');
|
|
||||||
|
|
||||||
// Handle client disconnection
|
|
||||||
// socket.on('disconnect', () => {
|
|
||||||
// console.log('A user disconnected');
|
|
||||||
// });
|
|
||||||
|
|
||||||
// // Handle custom events
|
|
||||||
// socket.on('chatMessage', (message) => {
|
|
||||||
// // Broadcast the message to all connected clients
|
|
||||||
// console.log(socket.handshake.auth.token);
|
|
||||||
|
|
||||||
// io.emit('chatMessage', message);
|
|
||||||
// });
|
|
||||||
});
|
|
||||||
|
|
||||||
// Start the HTTP server
|
|
||||||
server.listen(process.env.port, () => {
|
|
||||||
console.log(`Server is running on port ${process.env.port}`);
|
|
||||||
});
|
|
||||||
24
test/app.e2e-spec.ts
Normal file
24
test/app.e2e-spec.ts
Normal 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!');
|
||||||
|
});
|
||||||
|
});
|
||||||
9
test/jest-e2e.json
Normal file
9
test/jest-e2e.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": ["js", "json", "ts"],
|
||||||
|
"rootDir": ".",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
}
|
||||||
|
}
|
||||||
4
tsconfig.build.json
Normal file
4
tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
||||||
122
tsconfig.json
122
tsconfig.json
@@ -1,109 +1,21 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
/* Visit https://aka.ms/tsconfig to read more about this file */
|
"module": "commonjs",
|
||||||
|
"declaration": true,
|
||||||
/* Projects */
|
"removeComments": true,
|
||||||
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
"emitDecoratorMetadata": true,
|
||||||
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
"experimentalDecorators": true,
|
||||||
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
"allowSyntheticDefaultImports": true,
|
||||||
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
"target": "ES2021",
|
||||||
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
"sourceMap": true,
|
||||||
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
/* Language and Environment */
|
"incremental": true,
|
||||||
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
"skipLibCheck": true,
|
||||||
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
"strictNullChecks": false,
|
||||||
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
"noImplicitAny": false,
|
||||||
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
"strictBindCallApply": false,
|
||||||
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
"forceConsistentCasingInFileNames": false,
|
||||||
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
"noFallthroughCasesInSwitch": false
|
||||||
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
|
||||||
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
|
||||||
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
|
||||||
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
|
||||||
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
|
||||||
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
|
||||||
|
|
||||||
/* Modules */
|
|
||||||
"module": "commonjs", /* Specify what module code is generated. */
|
|
||||||
// "rootDir": "./", /* Specify the root folder within your source files. */
|
|
||||||
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
|
||||||
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
|
|
||||||
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
|
||||||
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
|
||||||
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
|
|
||||||
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
|
||||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
|
||||||
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
|
||||||
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
|
||||||
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
|
||||||
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
|
||||||
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
|
||||||
// "resolveJsonModule": true, /* Enable importing .json files. */
|
|
||||||
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
|
||||||
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
|
||||||
|
|
||||||
/* JavaScript Support */
|
|
||||||
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
|
||||||
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
|
||||||
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
|
||||||
|
|
||||||
/* Emit */
|
|
||||||
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
|
||||||
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
|
||||||
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
|
||||||
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
|
||||||
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
|
||||||
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
|
||||||
// "outDir": "./", /* Specify an output folder for all emitted files. */
|
|
||||||
// "removeComments": true, /* Disable emitting comments. */
|
|
||||||
// "noEmit": true, /* Disable emitting files from a compilation. */
|
|
||||||
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
|
||||||
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
|
||||||
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
|
||||||
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
|
||||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
|
||||||
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
|
||||||
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
|
||||||
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
|
||||||
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
|
||||||
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
|
||||||
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
|
||||||
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
|
||||||
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
|
||||||
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
|
||||||
|
|
||||||
/* Interop Constraints */
|
|
||||||
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
|
||||||
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
|
||||||
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
|
||||||
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
|
||||||
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
|
||||||
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
|
||||||
|
|
||||||
/* Type Checking */
|
|
||||||
"strict": true, /* Enable all strict type-checking options. */
|
|
||||||
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
|
||||||
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
|
||||||
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
|
||||||
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
|
||||||
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
|
||||||
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
|
||||||
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
|
||||||
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
|
||||||
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
|
||||||
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
|
||||||
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
|
||||||
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
|
||||||
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
|
||||||
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
|
||||||
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
|
||||||
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
|
||||||
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
|
||||||
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
|
||||||
|
|
||||||
/* Completeness */
|
|
||||||
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
|
||||||
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user