Browse Source

feat: use websocket gateway instead of service

Signed-off-by: mertmit <mertmit99@gmail.com>
feat/export-nest
mertmit 1 year ago
parent
commit
ad2b4638bd
  1. 14
      packages/nocodb-nest/src/controllers/imports/import.controller.ts
  2. 6
      packages/nocodb-nest/src/modules/global/global.module.ts
  3. 31
      packages/nocodb-nest/src/services/socket.gateway.ts
  4. 19
      packages/nocodb-nest/src/services/socket.service.spec.ts

14
packages/nocodb-nest/src/controllers/imports/import.controller.ts

@ -1,12 +1,12 @@
import { Controller, HttpCode, Post, Request, UseGuards } from '@nestjs/common'; import { Controller, HttpCode, Post, Request, UseGuards } from '@nestjs/common';
import { forwardRef, Inject } from '@nestjs/common'; import { forwardRef, Inject } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core'; import { ModuleRef } from '@nestjs/core';
import { SocketGateway } from 'src/services/socket.gateway';
import { GlobalGuard } from '../../guards/global/global.guard'; import { GlobalGuard } from '../../guards/global/global.guard';
import { NcError } from '../../helpers/catchError'; import { NcError } from '../../helpers/catchError';
import { ExtractProjectIdMiddleware } from '../../middlewares/extract-project-id/extract-project-id.middleware'; import { ExtractProjectIdMiddleware } from '../../middlewares/extract-project-id/extract-project-id.middleware';
import { SyncSource } from '../../models'; import { SyncSource } from '../../models';
import NocoJobs from '../../jobs/NocoJobs'; import NocoJobs from '../../jobs/NocoJobs';
import { SocketService } from '../../services/socket.service';
import airtableSyncJob from './helpers/job'; import airtableSyncJob from './helpers/job';
import type { AirtableSyncConfig } from './helpers/job'; import type { AirtableSyncConfig } from './helpers/job';
@ -78,7 +78,7 @@ const initJob = (sv: Server, jobs: { [p: string]: { last_message: any } }) => {
@UseGuards(ExtractProjectIdMiddleware, GlobalGuard) @UseGuards(ExtractProjectIdMiddleware, GlobalGuard)
export class ImportController { export class ImportController {
constructor( constructor(
private readonly socketService: SocketService, private readonly socketGateway: SocketGateway,
@Inject(forwardRef(() => ModuleRef)) private readonly moduleRef: ModuleRef, @Inject(forwardRef(() => ModuleRef)) private readonly moduleRef: ModuleRef,
) {} ) {}
@ -95,7 +95,7 @@ export class ImportController {
@Post('/api/v1/db/meta/syncs/:syncId/trigger') @Post('/api/v1/db/meta/syncs/:syncId/trigger')
@HttpCode(200) @HttpCode(200)
async triggerSync(@Request() req) { async triggerSync(@Request() req) {
if (req.params.syncId in this.socketService.jobs) { if (req.params.syncId in this.socketGateway.jobs) {
NcError.badRequest('Sync already in progress'); NcError.badRequest('Sync already in progress');
} }
@ -125,7 +125,7 @@ export class ImportController {
}); });
}, 1000); }, 1000);
this.socketService.jobs[req.params.syncId] = { this.socketGateway.jobs[req.params.syncId] = {
last_message: { last_message: {
msg: 'Sync started', msg: 'Sync started',
}, },
@ -136,13 +136,13 @@ export class ImportController {
@Post('/api/v1/db/meta/syncs/:syncId/abort') @Post('/api/v1/db/meta/syncs/:syncId/abort')
@HttpCode(200) @HttpCode(200)
async abortImport(@Request() req) { async abortImport(@Request() req) {
if (req.params.syncId in this.socketService.jobs) { if (req.params.syncId in this.socketGateway.jobs) {
delete this.socketService.jobs[req.params.syncId]; delete this.socketGateway.jobs[req.params.syncId];
} }
return {}; return {};
} }
async onModuleInit() { async onModuleInit() {
initJob(this.socketService.io, this.socketService.jobs); initJob(this.socketGateway.io, this.socketGateway.jobs);
} }
} }

6
packages/nocodb-nest/src/modules/global/global.module.ts

@ -1,10 +1,10 @@
import { Global, Module } from '@nestjs/common'; import { Global, Module } from '@nestjs/common';
import { JwtModule, JwtService } from '@nestjs/jwt'; import { JwtModule, JwtService } from '@nestjs/jwt';
import { ExtractJwt } from 'passport-jwt'; import { ExtractJwt } from 'passport-jwt';
import { SocketGateway } from 'src/services/socket.gateway';
import { Connection } from '../../connection/connection'; import { Connection } from '../../connection/connection';
import { GlobalGuard } from '../../guards/global/global.guard'; import { GlobalGuard } from '../../guards/global/global.guard';
import { MetaService } from '../../meta/meta.service'; import { MetaService } from '../../meta/meta.service';
import { SocketService } from '../../services/socket.service';
import { JwtStrategy } from '../../strategies/jwt.strategy'; import { JwtStrategy } from '../../strategies/jwt.strategy';
import NcConfigFactory from '../../utils/NcConfigFactory'; import NcConfigFactory from '../../utils/NcConfigFactory';
import { UsersService } from '../../services/users/users.service'; import { UsersService } from '../../services/users/users.service';
@ -38,7 +38,7 @@ export const JwtStrategyProvider: Provider = {
UsersService, UsersService,
JwtStrategyProvider, JwtStrategyProvider,
GlobalGuard, GlobalGuard,
SocketService, SocketGateway,
], ],
exports: [ exports: [
Connection, Connection,
@ -46,7 +46,7 @@ export const JwtStrategyProvider: Provider = {
JwtStrategyProvider, JwtStrategyProvider,
UsersService, UsersService,
GlobalGuard, GlobalGuard,
SocketService, SocketGateway,
], ],
}) })
export class GlobalModule {} export class GlobalModule {}

31
packages/nocodb-nest/src/services/socket.service.ts → packages/nocodb-nest/src/services/socket.gateway.ts

@ -1,11 +1,11 @@
import crypto from 'crypto'; import crypto from 'crypto';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'; import { WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { Inject, Injectable } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core'; import { HttpAdapterHost } from '@nestjs/core';
import { T } from 'nc-help'; import { T } from 'nc-help';
import { Server } from 'socket.io'; import { Server } from 'socket.io';
import { AuthGuard } from '@nestjs/passport'; import { AuthGuard } from '@nestjs/passport';
import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host'; import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';
import Noco from '../Noco';
import { JwtStrategy } from '../strategies/jwt.strategy'; import { JwtStrategy } from '../strategies/jwt.strategy';
import type { OnModuleInit } from '@nestjs/common'; import type { OnModuleInit } from '@nestjs/common';
import type { Socket } from 'socket.io'; import type { Socket } from 'socket.io';
@ -14,30 +14,29 @@ function getHash(str) {
return crypto.createHash('md5').update(str).digest('hex'); return crypto.createHash('md5').update(str).digest('hex');
} }
@WebSocketGateway({
cors: {
origin: '*',
allowedHeaders: ['xc-auth'],
credentials: true,
},
})
@Injectable() @Injectable()
export class SocketService implements OnModuleInit { export class SocketGateway implements OnModuleInit {
// private server: HttpServer; // private server: HttpServer;
private clients: { [id: string]: Socket } = {}; private clients: { [id: string]: Socket } = {};
private _jobs: { [id: string]: { last_message: any } } = {}; private _jobs: { [id: string]: { last_message: any } } = {};
private _io: Server;
constructor( constructor(
private jwtStrategy: JwtStrategy, private jwtStrategy: JwtStrategy,
@Inject(HttpAdapterHost) private httpAdapterHost: HttpAdapterHost, @Inject(HttpAdapterHost) private httpAdapterHost: HttpAdapterHost,
) {} ) {}
@WebSocketServer()
server: Server;
async onModuleInit() { async onModuleInit() {
this._io = new Server( this.server
Noco.httpServer ?? this.httpAdapterHost.httpAdapter.getHttpServer(),
{
cors: {
origin: '*',
allowedHeaders: ['xc-auth'],
credentials: true,
},
},
);
this.io
.use(async (socket, next) => { .use(async (socket, next) => {
try { try {
const context = new ExecutionContextHost([socket.handshake as any]); const context = new ExecutionContextHost([socket.handshake as any]);
@ -71,7 +70,7 @@ export class SocketService implements OnModuleInit {
} }
public get io() { public get io() {
return this._io; return this.server;
} }
public get jobs() { public get jobs() {

19
packages/nocodb-nest/src/services/socket.service.spec.ts

@ -1,19 +0,0 @@
import { Test } from '@nestjs/testing';
import { SocketService } from './socket.service';
import type { TestingModule } from '@nestjs/testing';
describe('ClientService', () => {
let service: SocketService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [SocketService],
}).compile();
service = module.get<SocketService>(SocketService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
Loading…
Cancel
Save