mirror of
https://github.com/nestjs/nest.git
synced 2026-02-21 23:11:44 +00:00
refactor(common,core): use shared utils from common whenever possible
Use every util defined at `shared.utils.ts` from `@nestjs/common`, when possible. Only spec files aren't touched.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { Readable } from 'stream';
|
||||
import { isFunction } from '../utils/shared.utils';
|
||||
import { StreamableFileOptions } from './streamable-options.interface';
|
||||
|
||||
export class StreamableFile {
|
||||
@@ -14,10 +15,7 @@ export class StreamableFile {
|
||||
this.stream = new Readable();
|
||||
this.stream.push(bufferOrReadStream);
|
||||
this.stream.push(null);
|
||||
} else if (
|
||||
bufferOrReadStream.pipe &&
|
||||
typeof bufferOrReadStream.pipe === 'function'
|
||||
) {
|
||||
} else if (bufferOrReadStream.pipe && isFunction(bufferOrReadStream.pipe)) {
|
||||
this.stream = bufferOrReadStream;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
PipeTransform,
|
||||
} from '../interfaces/features/pipe-transform.interface';
|
||||
import { HttpErrorByCode } from '../utils/http-error-by-code.util';
|
||||
import { isNil, isString } from '../utils/shared.utils';
|
||||
import { isNil, isUndefined, isString } from '../utils/shared.utils';
|
||||
import { ValidationPipe, ValidationPipeOptions } from './validation.pipe';
|
||||
|
||||
const VALIDATION_ERROR_MESSAGE = 'Validation failed (parsable array expected)';
|
||||
@@ -141,21 +141,19 @@ export class ParseArrayPipe implements PipeTransform {
|
||||
originalValue !== null && originalValue !== '' ? +originalValue : NaN;
|
||||
if (isNaN(value)) {
|
||||
throw this.exceptionFactory(
|
||||
`${
|
||||
typeof index !== 'undefined' ? `[${index}] ` : ''
|
||||
}item must be a number`,
|
||||
`${isUndefined(index) ? '' : `[${index}] `}item must be a number`,
|
||||
);
|
||||
}
|
||||
return value;
|
||||
} else if (this.options.items === String) {
|
||||
if (typeof originalValue !== 'string') {
|
||||
if (!isString(originalValue)) {
|
||||
return `${originalValue}`;
|
||||
}
|
||||
} else if (this.options.items === Boolean) {
|
||||
if (typeof originalValue !== 'boolean') {
|
||||
throw this.exceptionFactory(
|
||||
`${
|
||||
typeof index !== 'undefined' ? `[${index}] ` : ''
|
||||
isUndefined(index) ? '' : `[${index}] `
|
||||
}item must be a boolean value`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
HttpErrorByCode,
|
||||
} from '../utils/http-error-by-code.util';
|
||||
import { loadPackage } from '../utils/load-package.util';
|
||||
import { isNil } from '../utils/shared.utils';
|
||||
import { isNil, isObject } from '../utils/shared.utils';
|
||||
|
||||
export interface ValidationPipeOptions extends ValidatorOptions {
|
||||
transform?: boolean;
|
||||
@@ -194,7 +194,7 @@ export class ValidationPipe implements PipeTransform<any> {
|
||||
delete value.__proto__;
|
||||
const keys = Object.keys(value);
|
||||
iterate(keys)
|
||||
.filter(key => typeof value[key] === 'object' && value[key])
|
||||
.filter(key => isObject(value[key]) && value[key])
|
||||
.forEach(key => this.stripProtoKeys(value[key]));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable } from '../decorators/core/injectable.decorator';
|
||||
import { Optional } from '../decorators/core/optional.decorator';
|
||||
import { clc, yellow } from '../utils/cli-colors.util';
|
||||
import { isPlainObject } from '../utils/shared.utils';
|
||||
import { isPlainObject, isString } from '../utils/shared.utils';
|
||||
import { LoggerService, LogLevel } from './logger.service';
|
||||
import { isLogLevelEnabled } from './utils';
|
||||
|
||||
@@ -226,7 +226,7 @@ export class ConsoleLogger implements LoggerService {
|
||||
return { messages: args, context: this.context };
|
||||
}
|
||||
const lastElement = args[args.length - 1];
|
||||
const isContext = typeof lastElement === 'string';
|
||||
const isContext = isString(lastElement);
|
||||
if (!isContext) {
|
||||
return { messages: args, context: this.context };
|
||||
}
|
||||
@@ -242,7 +242,7 @@ export class ConsoleLogger implements LoggerService {
|
||||
return { messages, context };
|
||||
}
|
||||
const lastElement = messages[messages.length - 1];
|
||||
const isStack = typeof lastElement === 'string';
|
||||
const isStack = isString(lastElement);
|
||||
if (!isStack) {
|
||||
return { messages, context };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { BadRequestException } from '../exceptions';
|
||||
import { isString } from './shared.utils';
|
||||
|
||||
const uuid = {
|
||||
3: /^[0-9A-F]{8}-[0-9A-F]{4}-3[0-9A-F]{3}-[0-9A-F]{4}-[0-9A-F]{12}$/i,
|
||||
@@ -8,7 +9,7 @@ const uuid = {
|
||||
};
|
||||
|
||||
export function isUUID(str: any, version = 'all') {
|
||||
if (typeof str !== 'string') {
|
||||
if (!isString(str)) {
|
||||
throw new BadRequestException('The value passed as UUID is not a string');
|
||||
}
|
||||
const pattern = uuid[version];
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { DynamicModule } from '@nestjs/common';
|
||||
import { Type } from '@nestjs/common/interfaces/type.interface';
|
||||
import { randomStringGenerator } from '@nestjs/common/utils/random-string-generator.util';
|
||||
import { isFunction, isSymbol } from '@nestjs/common/utils/shared.utils';
|
||||
import stringify from 'fast-safe-stringify';
|
||||
import * as hash from 'object-hash';
|
||||
|
||||
@@ -46,7 +47,7 @@ export class ModuleTokenFactory {
|
||||
}
|
||||
|
||||
private replacer(key: string, value: any) {
|
||||
if (typeof value === 'function') {
|
||||
if (isFunction(value)) {
|
||||
const funcAsString = value.toString();
|
||||
const isClass = /^class\s/.test(funcAsString);
|
||||
if (isClass) {
|
||||
@@ -54,7 +55,7 @@ export class ModuleTokenFactory {
|
||||
}
|
||||
return hash(funcAsString, { ignoreUnknown: true });
|
||||
}
|
||||
if (typeof value === 'symbol') {
|
||||
if (isSymbol(value)) {
|
||||
return value.toString();
|
||||
}
|
||||
return value;
|
||||
|
||||
@@ -81,7 +81,7 @@ export function isMiddlewareClass(middleware: any): middleware is Type<any> {
|
||||
return (
|
||||
middlewareArr[0] === 'function' &&
|
||||
/[A-Z]/.test(middlewareArr[1]?.[0]) &&
|
||||
typeof middleware.prototype?.use === 'function'
|
||||
isFunction(middleware.prototype?.use)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -121,8 +121,7 @@ export class NestApplication
|
||||
return undefined;
|
||||
}
|
||||
const passCustomOptions =
|
||||
isObject(this.appOptions.cors) ||
|
||||
typeof this.appOptions.cors === 'function';
|
||||
isObject(this.appOptions.cors) || isFunction(this.appOptions.cors);
|
||||
if (!passCustomOptions) {
|
||||
return this.enableCors();
|
||||
}
|
||||
@@ -319,13 +318,14 @@ export class NestApplication
|
||||
}
|
||||
|
||||
private formatAddress(address: any): string {
|
||||
if (typeof address === 'string') {
|
||||
if (isString(address)) {
|
||||
if (platform() === 'win32') {
|
||||
return address;
|
||||
}
|
||||
const basePath = encodeURIComponent(address);
|
||||
return `${this.getProtocol()}+unix://${basePath}`;
|
||||
}
|
||||
|
||||
let host = this.host();
|
||||
if (address && address.family === 'IPv6') {
|
||||
if (host === '::') {
|
||||
@@ -410,7 +410,7 @@ export class NestApplication
|
||||
}
|
||||
private host(): string | undefined {
|
||||
const address = this.httpServer.address();
|
||||
if (typeof address === 'string') {
|
||||
if (isString(address)) {
|
||||
return undefined;
|
||||
}
|
||||
return address && address.address;
|
||||
|
||||
@@ -424,7 +424,7 @@ export class RouterExecutionContext {
|
||||
);
|
||||
};
|
||||
}
|
||||
if (redirectResponse && typeof redirectResponse.url === 'string') {
|
||||
if (redirectResponse && isString(redirectResponse.url)) {
|
||||
return async <TResult, TResponse>(result: TResult, res: TResponse) => {
|
||||
await this.responseController.redirect(result, res, redirectResponse);
|
||||
};
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { MessageEvent } from '@nestjs/common/interfaces';
|
||||
import { isObject } from '@nestjs/common/utils/shared.utils';
|
||||
import { IncomingMessage, OutgoingHttpHeaders } from 'http';
|
||||
import { Transform } from 'stream';
|
||||
|
||||
function toDataString(data: string | object): string {
|
||||
if (typeof data === 'object') {
|
||||
if (isObject(data)) {
|
||||
return toDataString(JSON.stringify(data));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { normalizePath } from '@nestjs/common/utils/shared.utils';
|
||||
import { normalizePath, isString } from '@nestjs/common/utils/shared.utils';
|
||||
import { Routes } from '../interfaces/routes.interface';
|
||||
|
||||
export function flattenRoutePaths(routes: Routes) {
|
||||
@@ -10,7 +10,7 @@ export function flattenRoutePaths(routes: Routes) {
|
||||
if (item.children) {
|
||||
const childrenRef = item.children as Routes;
|
||||
childrenRef.forEach(child => {
|
||||
if (typeof child !== 'string' && child.path) {
|
||||
if (!isString(child) && child.path) {
|
||||
child.path = normalizePath(
|
||||
normalizePath(item.path) + normalizePath(child.path),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Logger } from '@nestjs/common/services/logger.service';
|
||||
import { loadPackage } from '@nestjs/common/utils/load-package.util';
|
||||
import { isObject } from '@nestjs/common/utils/shared.utils';
|
||||
import { NATS_DEFAULT_URL } from '../constants';
|
||||
import { NatsResponseJSONDeserializer } from '../deserializers/nats-response-json.deserializer';
|
||||
import { EmptyResponseException } from '../errors/empty-response.exception';
|
||||
@@ -48,7 +49,7 @@ export class ClientNats extends ClientProxy {
|
||||
public async handleStatusUpdates(client: Client) {
|
||||
for await (const status of client.status()) {
|
||||
const data =
|
||||
status.data && typeof status.data === 'object'
|
||||
status.data && isObject(status.data)
|
||||
? JSON.stringify(status.data)
|
||||
: status.data;
|
||||
if (status.type === 'disconnect' || status.type === 'error') {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isObject } from '@nestjs/common/utils/shared.utils';
|
||||
import { ReadPacket } from '../interfaces';
|
||||
import { Serializer } from '../interfaces/serializer.interface';
|
||||
import { MqttRecord } from '../record-builders';
|
||||
@@ -8,7 +9,7 @@ export class MqttRecordSerializer
|
||||
serialize(packet: ReadPacket | any): ReadPacket & Partial<MqttRecord> {
|
||||
if (
|
||||
packet?.data &&
|
||||
typeof packet.data === 'object' &&
|
||||
isObject(packet.data) &&
|
||||
packet.data instanceof MqttRecord
|
||||
) {
|
||||
const record = packet.data as MqttRecord;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isObject } from '@nestjs/common/utils/shared.utils';
|
||||
import { ReadPacket } from '../interfaces';
|
||||
import { Serializer } from '../interfaces/serializer.interface';
|
||||
import { RmqRecord } from '../record-builders';
|
||||
@@ -8,7 +9,7 @@ export class RmqRecordSerializer
|
||||
serialize(packet: ReadPacket | any): ReadPacket & Partial<RmqRecord> {
|
||||
if (
|
||||
packet?.data &&
|
||||
typeof packet.data === 'object' &&
|
||||
isObject(packet.data) &&
|
||||
packet.data instanceof RmqRecord
|
||||
) {
|
||||
const record = packet.data as RmqRecord;
|
||||
|
||||
@@ -292,7 +292,7 @@ export class ServerGrpc extends Server implements CustomTransportStrategy {
|
||||
),
|
||||
);
|
||||
|
||||
if (typeof response !== 'undefined') {
|
||||
if (!isUndefined(response)) {
|
||||
callback(null, response);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { isUndefined } from '@nestjs/common/utils/shared.utils';
|
||||
import { isUndefined, isObject } from '@nestjs/common/utils/shared.utils';
|
||||
import { Observable } from 'rxjs';
|
||||
import { NATS_DEFAULT_URL, NO_MESSAGE_HANDLER } from '../constants';
|
||||
import { NatsContext } from '../ctx-host/nats.context';
|
||||
@@ -134,7 +134,7 @@ export class ServerNats extends Server implements CustomTransportStrategy {
|
||||
public async handleStatusUpdates(client: Client) {
|
||||
for await (const status of client.status()) {
|
||||
const data =
|
||||
status.data && typeof status.data === 'object'
|
||||
status.data && isObject(status.data)
|
||||
? JSON.stringify(status.data)
|
||||
: status.data;
|
||||
if (status.type === 'disconnect' || status.type === 'error') {
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
CorsOptionsDelegate,
|
||||
} from '@nestjs/common/interfaces/external/cors-options.interface';
|
||||
import { loadPackage } from '@nestjs/common/utils/load-package.util';
|
||||
import { isUndefined, isString } from '@nestjs/common/utils/shared.utils';
|
||||
import { AbstractHttpAdapter } from '@nestjs/core/adapters/http-adapter';
|
||||
import {
|
||||
fastify,
|
||||
@@ -107,7 +108,7 @@ export class FastifyAdapter<
|
||||
private readonly versionConstraint = {
|
||||
name: 'version',
|
||||
validate(value: unknown) {
|
||||
if (typeof value !== 'string' && !Array.isArray(value)) {
|
||||
if (!isString(value) && !Array.isArray(value)) {
|
||||
throw new Error(
|
||||
'Version constraint should be a string or an array of strings.',
|
||||
);
|
||||
@@ -370,7 +371,7 @@ export class FastifyAdapter<
|
||||
}
|
||||
|
||||
public setViewEngine(options: PointOfViewOptions | string) {
|
||||
if (typeof options === 'string') {
|
||||
if (isString(options)) {
|
||||
new Logger('FastifyAdapter').error(
|
||||
"setViewEngine() doesn't support a string argument.",
|
||||
);
|
||||
@@ -477,7 +478,7 @@ export class FastifyAdapter<
|
||||
) {
|
||||
const handlerRef = args[args.length - 1];
|
||||
const isVersioned =
|
||||
typeof handlerRef.version !== 'undefined' &&
|
||||
!isUndefined(handlerRef.version) &&
|
||||
handlerRef.version !== VERSION_NEUTRAL;
|
||||
|
||||
if (isVersioned) {
|
||||
|
||||
Reference in New Issue
Block a user