refactor: remove deprecated apis from 3rd-party deps

Replacie old and deprecated APIs from `rxjs`, `body-parser`
and NodeJS core (read this guide https://nodejs.org/en/docs/guides/buffer-constructor-deprecation).
Do notice that the later only touches test files, thus doesn't affect
production code.
This commit is contained in:
Micael Levi (lab)
2021-12-23 22:23:44 -04:00
parent f1b9b636a5
commit fd720e899d
16 changed files with 79 additions and 66 deletions

View File

@@ -134,8 +134,8 @@ export class AdvancedGrpcController {
async streamReq(messages: Observable<any>): Promise<any> { async streamReq(messages: Observable<any>): Promise<any> {
const s = new Subject(); const s = new Subject();
const o = s.asObservable(); const o = s.asObservable();
messages.subscribe( messages.subscribe({
msg => { next: () => {
s.next({ s.next({
id: 1, id: 1,
itemTypes: [1], itemTypes: [1],
@@ -146,9 +146,8 @@ export class AdvancedGrpcController {
}, },
}); });
}, },
null, complete: () => s.complete(),
() => s.complete(), });
);
return o; return o;
} }

View File

@@ -50,16 +50,16 @@ export class GrpcController {
@GrpcStreamMethod('Math') @GrpcStreamMethod('Math')
async sumStream(messages: Observable<any>): Promise<any> { async sumStream(messages: Observable<any>): Promise<any> {
return new Promise<any>((resolve, reject) => { return new Promise<any>((resolve, reject) => {
messages.subscribe( messages.subscribe({
msg => { next: msg => {
resolve({ resolve({
result: msg.data.reduce((a, b) => a + b), result: msg.data.reduce((a, b) => a + b),
}); });
}, },
err => { error: err => {
reject(err); reject(err);
}, },
); });
}); });
} }

View File

@@ -17,7 +17,7 @@ export class BaseRpcExceptionFilter<T = any, R = any>
} }
const res = exception.getError(); const res = exception.getError();
const message = isObject(res) ? res : { status, message: res }; const message = isObject(res) ? res : { status, message: res };
return _throw(message); return _throw(() => message);
} }
public handleUnknownError(exception: T, status: string) { public handleUnknownError(exception: T, status: string) {
@@ -29,7 +29,7 @@ export class BaseRpcExceptionFilter<T = any, R = any>
const logger = BaseRpcExceptionFilter.logger; const logger = BaseRpcExceptionFilter.logger;
logger.error.apply(logger, loggerArgs as any); logger.error.apply(logger, loggerArgs as any);
return _throw({ status, message: errorMessage }); return _throw(() => ({ status, message: errorMessage }));
} }
public isError(exception: any): exception is Error { public isError(exception: any): exception is Error {

View File

@@ -220,10 +220,10 @@ export class ServerGrpc extends Server implements CustomTransportStrategy {
public createUnaryServiceMethod(methodHandler: Function): Function { public createUnaryServiceMethod(methodHandler: Function): Function {
return async (call: GrpcCall, callback: Function) => { return async (call: GrpcCall, callback: Function) => {
const handler = methodHandler(call.request, call.metadata, call); const handler = methodHandler(call.request, call.metadata, call);
this.transformToObservable(await handler).subscribe( this.transformToObservable(await handler).subscribe({
data => callback(null, data), next: data => callback(null, data),
(err: any) => callback(err), error: (err: any) => callback(err),
); });
}; };
} }

View File

@@ -2,7 +2,7 @@ import { Logger, LoggerService } from '@nestjs/common/services/logger.service';
import { loadPackage } from '@nestjs/common/utils/load-package.util'; import { loadPackage } from '@nestjs/common/utils/load-package.util';
import { import {
connectable, connectable,
EMPTY as empty, EMPTY,
from as fromPromise, from as fromPromise,
isObservable, isObservable,
Observable, Observable,
@@ -94,7 +94,7 @@ export abstract class Server {
.pipe( .pipe(
catchError((err: any) => { catchError((err: any) => {
scheduleOnNextTick({ err }); scheduleOnNextTick({ err });
return empty; return EMPTY;
}), }),
finalize(() => scheduleOnNextTick({ isDisposed: true })), finalize(() => scheduleOnNextTick({ isDisposed: true })),
) )

View File

@@ -129,10 +129,10 @@ describe('ClientGrpcProxy', () => {
it('should call native method', () => { it('should call native method', () => {
const spy = sinon.spy(obj, methodName); const spy = sinon.spy(obj, methodName);
stream$.subscribe( stream$.subscribe({
() => ({}), next: () => ({}),
() => ({}), error: () => ({}),
); });
expect(spy.called).to.be.true; expect(spy.called).to.be.true;
}); });
@@ -156,10 +156,10 @@ describe('ClientGrpcProxy', () => {
it('should subscribe to request upstream', () => { it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe'); const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe( stream$.subscribe({
() => ({}), next: () => ({}),
() => ({}), error: () => ({}),
); });
upstream.next({ test: true }); upstream.next({ test: true });
expect(writeSpy.called).to.be.true; expect(writeSpy.called).to.be.true;
@@ -201,7 +201,12 @@ describe('ClientGrpcProxy', () => {
it('propagates server errors', () => { it('propagates server errors', () => {
const err = new Error('something happened'); const err = new Error('something happened');
stream$.subscribe(dataSpy, errorSpy, completeSpy); stream$.subscribe({
next: dataSpy,
error: errorSpy,
complete: completeSpy,
});
eventCallbacks.data('a'); eventCallbacks.data('a');
eventCallbacks.data('b'); eventCallbacks.data('b');
callMock.finished = true; callMock.finished = true;
@@ -219,7 +224,11 @@ describe('ClientGrpcProxy', () => {
const grpcServerCancelErrMock = { const grpcServerCancelErrMock = {
details: 'Cancelled', details: 'Cancelled',
}; };
const subscription = stream$.subscribe(dataSpy, errorSpy); const subscription = stream$.subscribe({
next: dataSpy,
error: errorSpy,
});
eventCallbacks.data('a'); eventCallbacks.data('a');
eventCallbacks.data('b'); eventCallbacks.data('b');
subscription.unsubscribe(); subscription.unsubscribe();
@@ -258,10 +267,10 @@ describe('ClientGrpcProxy', () => {
it('should call native method', () => { it('should call native method', () => {
const spy = sinon.spy(obj, methodName); const spy = sinon.spy(obj, methodName);
stream$.subscribe( stream$.subscribe({
() => ({}), next: () => ({}),
() => ({}), error: () => ({}),
); });
expect(spy.called).to.be.true; expect(spy.called).to.be.true;
}); });
@@ -298,10 +307,10 @@ describe('ClientGrpcProxy', () => {
it('should subscribe to request upstream', () => { it('should subscribe to request upstream', () => {
const upstreamSubscribe = sinon.spy(upstream, 'subscribe'); const upstreamSubscribe = sinon.spy(upstream, 'subscribe');
stream$.subscribe( stream$.subscribe({
() => ({}), next: () => ({}),
() => ({}), error: () => ({}),
); });
upstream.next({ test: true }); upstream.next({ test: true });
expect(writeSpy.called).to.be.true; expect(writeSpy.called).to.be.true;

View File

@@ -1,5 +1,5 @@
import { expect } from 'chai'; import { expect } from 'chai';
import { empty } from 'rxjs'; import { EMPTY } from 'rxjs';
import * as sinon from 'sinon'; import * as sinon from 'sinon';
import { ClientMqtt } from '../../client/client-mqtt'; import { ClientMqtt } from '../../client/client-mqtt';
import { ERROR_EVENT } from '../../constants'; import { ERROR_EVENT } from '../../constants';
@@ -311,9 +311,9 @@ describe('ClientMqtt', () => {
on: (ev, callback) => callback(error), on: (ev, callback) => callback(error),
off: () => ({}), off: () => ({}),
}; };
client client.mergeCloseEvent(instance as any, EMPTY).subscribe({
.mergeCloseEvent(instance as any, empty()) error: (err: any) => expect(err).to.be.eql(error),
.subscribe(null, (err: any) => expect(err).to.be.eql(error)); });
}); });
}); });
describe('handleError', () => { describe('handleError', () => {

View File

@@ -96,12 +96,12 @@ describe('ClientProxy', function () {
throw new Error(); throw new Error();
}); });
const stream$ = client.send({ test: 3 }, 'test'); const stream$ = client.send({ test: 3 }, 'test');
stream$.subscribe( stream$.subscribe({
() => {}, next: () => {},
err => { error: err => {
expect(err).to.be.instanceof(Error); expect(err).to.be.instanceof(Error);
}, },
); });
}); });
}); });
describe('when is connected', () => { describe('when is connected', () => {
@@ -142,12 +142,12 @@ describe('ClientProxy', function () {
throw new Error(); throw new Error();
}); });
const stream$ = client.emit({ test: 3 }, 'test'); const stream$ = client.emit({ test: 3 }, 'test');
stream$.subscribe( stream$.subscribe({
() => {}, next: () => {},
err => { error: err => {
expect(err).to.be.instanceof(Error); expect(err).to.be.instanceof(Error);
}, },
); });
}); });
}); });
describe('when is connected', () => { describe('when is connected', () => {

View File

@@ -1,6 +1,6 @@
import { expect } from 'chai'; import { expect } from 'chai';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { empty } from 'rxjs'; import { EMPTY } from 'rxjs';
import * as sinon from 'sinon'; import * as sinon from 'sinon';
import { ClientRMQ } from '../../client/client-rmq'; import { ClientRMQ } from '../../client/client-rmq';
import { ReadPacket } from '../../interfaces'; import { ReadPacket } from '../../interfaces';
@@ -164,8 +164,8 @@ describe('ClientRMQ', function () {
off: () => ({}), off: () => ({}),
}; };
client client
.mergeDisconnectEvent(instance as any, empty()) .mergeDisconnectEvent(instance as any, EMPTY)
.subscribe(null, (err: any) => expect(err).to.be.eql(error)); .subscribe({ error: (err: any) => expect(err).to.be.eql(error) });
}); });
}); });

View File

@@ -36,7 +36,9 @@ describe('RpcProxy', () => {
const proxy = routerProxy.create(async (client, data) => { const proxy = routerProxy.create(async (client, data) => {
return throwError(() => new RpcException('test')); return throwError(() => new RpcException('test'));
}, handler); }, handler);
(await proxy(null, null)).subscribe(null, () => expectation.verify()); (await proxy(null, null)).subscribe({
error: () => expectation.verify(),
});
}); });
}); });
}); });

View File

@@ -1,5 +1,5 @@
import { expect } from 'chai'; import { expect } from 'chai';
import { EMPTY as empty, of } from 'rxjs'; import { EMPTY, of } from 'rxjs';
import { catchError } from 'rxjs/operators'; import { catchError } from 'rxjs/operators';
import * as sinon from 'sinon'; import * as sinon from 'sinon';
import { RpcException } from '../../exceptions/rpc-exception'; import { RpcException } from '../../exceptions/rpc-exception';
@@ -23,7 +23,7 @@ describe('RpcExceptionsHandler', () => {
message: 'Internal server error', message: 'Internal server error',
}); });
done(); done();
return empty; return EMPTY;
}), }),
) )
.subscribe(() => ({})); .subscribe(() => ({}));
@@ -39,7 +39,7 @@ describe('RpcExceptionsHandler', () => {
catchError((err: any) => { catchError((err: any) => {
expect(err).to.be.eql(message); expect(err).to.be.eql(message);
done(); done();
return empty; return EMPTY;
}), }),
) )
.subscribe(() => ({})); .subscribe(() => ({}));
@@ -53,7 +53,7 @@ describe('RpcExceptionsHandler', () => {
catchError((err: any) => { catchError((err: any) => {
expect(err).to.be.eql({ message, status: 'error' }); expect(err).to.be.eql({ message, status: 'error' });
done(); done();
return empty; return EMPTY;
}), }),
) )
.subscribe(() => ({})); .subscribe(() => ({}));

View File

@@ -112,7 +112,7 @@ describe('ServerMqtt', () => {
const handleEventSpy = sinon.spy(server, 'handleEvent'); const handleEventSpy = sinon.spy(server, 'handleEvent');
await server.handleMessage( await server.handleMessage(
channel, channel,
new Buffer(JSON.stringify({ pattern: '', data })), Buffer.from(JSON.stringify({ pattern: '', data })),
null, null,
); );
expect(handleEventSpy.called).to.be.true; expect(handleEventSpy.called).to.be.true;
@@ -120,7 +120,7 @@ describe('ServerMqtt', () => {
it(`should publish NO_MESSAGE_HANDLER if pattern not exists in messageHandlers object`, async () => { it(`should publish NO_MESSAGE_HANDLER if pattern not exists in messageHandlers object`, async () => {
await server.handleMessage( await server.handleMessage(
channel, channel,
new Buffer(JSON.stringify({ id, pattern: '', data })), Buffer.from(JSON.stringify({ id, pattern: '', data })),
null, null,
); );
expect( expect(
@@ -139,7 +139,7 @@ describe('ServerMqtt', () => {
await server.handleMessage( await server.handleMessage(
channel, channel,
new Buffer(JSON.stringify({ pattern: '', data, id: '2' })), Buffer.from(JSON.stringify({ pattern: '', data, id: '2' })),
null, null,
); );
expect(handler.calledWith(data)).to.be.true; expect(handler.calledWith(data)).to.be.true;

View File

@@ -116,7 +116,7 @@ describe('Server', () => {
}); });
describe('throws exception', () => { describe('throws exception', () => {
beforeEach(() => { beforeEach(() => {
server.send(_throw('test') as any, sendSpy); server.send(_throw(() => 'test') as any, sendSpy);
}); });
it('should send error and complete', () => { it('should send error and complete', () => {
process.nextTick(() => { process.nextTick(() => {

View File

@@ -22,7 +22,10 @@ import {
} from '@nestjs/common/utils/shared.utils'; } from '@nestjs/common/utils/shared.utils';
import { AbstractHttpAdapter } from '@nestjs/core/adapters/http-adapter'; import { AbstractHttpAdapter } from '@nestjs/core/adapters/http-adapter';
import { RouterMethodFactory } from '@nestjs/core/helpers/router-method-factory'; import { RouterMethodFactory } from '@nestjs/core/helpers/router-method-factory';
import * as bodyParser from 'body-parser'; import {
json as bodyParserJson,
urlencoded as bodyParserUrlencoded,
} from 'body-parser';
import * as cors from 'cors'; import * as cors from 'cors';
import * as express from 'express'; import * as express from 'express';
import * as http from 'http'; import * as http from 'http';
@@ -162,8 +165,8 @@ export class ExpressAdapter extends AbstractHttpAdapter {
public registerParserMiddleware() { public registerParserMiddleware() {
const parserMiddleware = { const parserMiddleware = {
jsonParser: bodyParser.json(), jsonParser: bodyParserJson(),
urlencodedParser: bodyParser.urlencoded({ extended: true }), urlencodedParser: bodyParserUrlencoded({ extended: true }),
}; };
Object.keys(parserMiddleware) Object.keys(parserMiddleware)
.filter(parser => !this.isMiddlewareApplied(parser)) .filter(parser => !this.isMiddlewareApplied(parser))

View File

@@ -8,7 +8,7 @@ import {
} from '@nestjs/websockets/constants'; } from '@nestjs/websockets/constants';
import { MessageMappingProperties } from '@nestjs/websockets/gateway-metadata-explorer'; import { MessageMappingProperties } from '@nestjs/websockets/gateway-metadata-explorer';
import * as http from 'http'; import * as http from 'http';
import { EMPTY as empty, fromEvent, Observable } from 'rxjs'; import { EMPTY, fromEvent, Observable } from 'rxjs';
import { filter, first, mergeMap, share, takeUntil } from 'rxjs/operators'; import { filter, first, mergeMap, share, takeUntil } from 'rxjs/operators';
let wsPackage: any = {}; let wsPackage: any = {};
@@ -133,7 +133,7 @@ export class WsAdapter extends AbstractWsAdapter {
const { callback } = messageHandler; const { callback } = messageHandler;
return transform(callback(message.data)); return transform(callback(message.data));
} catch { } catch {
return empty; return EMPTY;
} }
} }

View File

@@ -1,5 +1,5 @@
import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host'; import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host';
import { empty, isObservable } from 'rxjs'; import { EMPTY, isObservable } from 'rxjs';
import { catchError } from 'rxjs/operators'; import { catchError } from 'rxjs/operators';
import { WsExceptionsHandler } from '../exceptions/ws-exceptions-handler'; import { WsExceptionsHandler } from '../exceptions/ws-exceptions-handler';
@@ -16,7 +16,7 @@ export class WsProxy {
: result.pipe( : result.pipe(
catchError(error => { catchError(error => {
this.handleError(exceptionsHandler, args, error); this.handleError(exceptionsHandler, args, error);
return empty(); return EMPTY;
}), }),
); );
} catch (error) { } catch (error) {