format() run prettier, update format script

This commit is contained in:
Kamil Myśliwiec
2019-10-04 09:08:27 +02:00
parent 63dfd5ec3a
commit 489d3299c0
91 changed files with 882 additions and 695 deletions

View File

@@ -1,8 +1,12 @@
import * as request from 'supertest';
import { Test } from '@nestjs/testing';
import { INestApplication, Injectable, UnauthorizedException } from '@nestjs/common';
import { ApplicationModule } from '../src/app.module';
import {
INestApplication,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { APP_GUARD } from '@nestjs/core';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { ApplicationModule } from '../src/app.module';
@Injectable()
export class AuthGuard {
@@ -30,9 +34,7 @@ describe('Guards', () => {
let app: INestApplication;
it(`should prevent access (unauthorized)`, async () => {
app = (await createTestModule(
new AuthGuard(),
)).createNestApplication();
app = (await createTestModule(new AuthGuard())).createNestApplication();
await app.init();
return request(app.getHttpServer())

View File

@@ -10,8 +10,7 @@ describe('Hello world (default adapter)', () => {
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [ApplicationModule],
})
.compile();
}).compile();
app = module.createNestApplication();
server = app.getHttpServer();

View File

@@ -10,8 +10,7 @@ describe('Hello world (default adapter)', () => {
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [ApplicationModule],
})
.compile();
}).compile();
app = module.createNestApplication();
server = app.getHttpServer();

View File

@@ -38,17 +38,15 @@ describe('BeforeApplicationShutdown', () => {
app.close();
expect(((module as any).dispose as Sinon.SinonSpy).called, 'dispose')
.to.be.false;
expect(((module as any).dispose as Sinon.SinonSpy).called, 'dispose').to.be
.false;
resolve();
setTimeout(
() =>
expect(
((module as any).dispose as Sinon.SinonSpy).called,
'dispose',
).to.be.true,
expect(((module as any).dispose as Sinon.SinonSpy).called, 'dispose').to
.be.true,
0,
);
});

View File

@@ -23,22 +23,22 @@ describe('OnApplicationBootstrap', () => {
it('should not throw an error when onApplicationBootstrap is null', async () => {
const module = await Test.createTestingModule({
providers: [
{ provide: 'TEST', useValue: { onApplicationBootstrap: null } }
{ provide: 'TEST', useValue: { onApplicationBootstrap: null } },
],
}).compile();
const app = module.createNestApplication();
await app.init().then((obj) => expect(obj).to.not.be.undefined);
await app.init().then(obj => expect(obj).to.not.be.undefined);
});
it('should not throw an error when onApplicationBootstrap is undefined', async () => {
const module = await Test.createTestingModule({
providers: [
{ provide: 'TEST', useValue: { onApplicationBootstrap: undefined } }
{ provide: 'TEST', useValue: { onApplicationBootstrap: undefined } },
],
}).compile();
const app = module.createNestApplication();
await app.init().then((obj) => expect(obj).to.not.be.undefined);
await app.init().then(obj => expect(obj).to.not.be.undefined);
});
});

View File

@@ -1,7 +1,7 @@
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { expect } from 'chai';
import * as Sinon from 'sinon';
import { Injectable, OnModuleDestroy } from '@nestjs/common';
@Injectable()
class TestInjectable implements OnModuleDestroy {
@@ -22,23 +22,21 @@ describe('OnModuleDestroy', () => {
it('should not throw an error when onModuleDestroy is null', async () => {
const module = await Test.createTestingModule({
providers: [
{ provide: 'TEST', useValue: { onModuleDestroy: null } }
],
providers: [{ provide: 'TEST', useValue: { onModuleDestroy: null } }],
}).compile();
const app = module.createNestApplication();
await app.init().then((obj) => expect(obj).to.not.be.undefined);
await app.init().then(obj => expect(obj).to.not.be.undefined);
});
it('should not throw an error when onModuleDestroy is undefined', async () => {
const module = await Test.createTestingModule({
providers: [
{ provide: 'TEST', useValue: { onModuleDestroy: undefined } }
{ provide: 'TEST', useValue: { onModuleDestroy: undefined } },
],
}).compile();
const app = module.createNestApplication();
await app.init().then((obj) => expect(obj).to.not.be.undefined);
await app.init().then(obj => expect(obj).to.not.be.undefined);
});
});

View File

@@ -22,23 +22,19 @@ describe('OnModuleInit', () => {
it('should not throw an error when onModuleInit is null', async () => {
const module = await Test.createTestingModule({
providers: [
{ provide: 'TEST', useValue: { onModuleInit: null } }
],
providers: [{ provide: 'TEST', useValue: { onModuleInit: null } }],
}).compile();
const app = module.createNestApplication();
await app.init().then((obj) => expect(obj).to.not.be.undefined);
await app.init().then(obj => expect(obj).to.not.be.undefined);
});
it('should not throw an error when onModuleInit is undefined', async () => {
const module = await Test.createTestingModule({
providers: [
{ provide: 'TEST', useValue: { onModuleInit: undefined } }
],
providers: [{ provide: 'TEST', useValue: { onModuleInit: undefined } }],
}).compile();
const app = module.createNestApplication();
await app.init().then((obj) => expect(obj).to.not.be.undefined);
await app.init().then(obj => expect(obj).to.not.be.undefined);
});
});

View File

@@ -1,10 +1,16 @@
import { Injectable, OnApplicationShutdown, BeforeApplicationShutdown, Module } from '@nestjs/common';
import {
Injectable,
OnApplicationShutdown,
BeforeApplicationShutdown,
Module,
} from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
const SIGNAL = process.argv[2];
const SIGNAL_TO_LISTEN = process.argv[3];
@Injectable()
class TestInjectable implements OnApplicationShutdown, BeforeApplicationShutdown {
class TestInjectable
implements OnApplicationShutdown, BeforeApplicationShutdown {
beforeApplicationShutdown(signal: string) {
console.log('beforeApplicationShutdown ' + signal);
}

View File

@@ -30,7 +30,9 @@ describe('Core Injectables', () => {
});
it('should provide the current Module as provider', () => {
const module = testingModule.get<CoreInjectablesModule>(CoreInjectablesModule);
const module = testingModule.get<CoreInjectablesModule>(
CoreInjectablesModule,
);
expect(module).to.not.be.undefined;
expect(module.constructor.name).to.be.eq('CoreInjectablesModule');
});

View File

@@ -5,9 +5,7 @@ export class CircularModule {
static forRoot(): DynamicModule {
const a = {
module: CircularModule,
providers: [
InputService,
],
providers: [InputService],
b: null,
};
a.b = a;

View File

@@ -1,5 +1,4 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class InputService {
}
export class InputService {}

View File

@@ -1,8 +1,8 @@
import { Controller, Get } from '@nestjs/common';
import {
Client,
MessagePattern,
ClientProxy,
MessagePattern,
Transport,
} from '@nestjs/microservices';
import { Observable } from 'rxjs';
@@ -15,9 +15,10 @@ export class MqttBroadcastController {
@Get('broadcast')
multicats() {
return this.client
.send<number>({ cmd: 'broadcast' }, {})
.pipe(scan((a, b) => a + b), take(2));
return this.client.send<number>({ cmd: 'broadcast' }, {}).pipe(
scan((a, b) => a + b),
take(2),
);
}
@MessagePattern({ cmd: 'broadcast' })

View File

@@ -15,9 +15,10 @@ export class NatsBroadcastController {
@Get('broadcast')
multicats() {
return this.client
.send<number>('broadcast.test', {})
.pipe(scan((a, b) => a + b), take(2));
return this.client.send<number>('broadcast.test', {}).pipe(
scan((a, b) => a + b),
take(2),
);
}
@MessagePattern('broadcast.*')

View File

@@ -15,8 +15,7 @@ export class RedisBroadcastController {
@Get('broadcast')
multicats() {
return this.client.send<number>({ cmd: 'broadcast' }, {})
.pipe(
return this.client.send<number>({ cmd: 'broadcast' }, {}).pipe(
scan((a, b) => a + b),
take(2),
);
@@ -24,6 +23,6 @@ export class RedisBroadcastController {
@MessagePattern({ cmd: 'broadcast' })
replyBroadcast(): Observable<number> {
return new Observable((observer) => observer.next(1));
return new Observable(observer => observer.next(1));
}
}

View File

@@ -26,9 +26,10 @@ export class RMQBroadcastController {
@Get('broadcast')
multicats() {
return this.client
.send<number>({ cmd: 'broadcast' }, {})
.pipe(scan((a, b) => a + b), take(2));
return this.client.send<number>({ cmd: 'broadcast' }, {}).pipe(
scan((a, b) => a + b),
take(2),
);
}
@MessagePattern({ cmd: 'broadcast' })

View File

@@ -3,9 +3,6 @@ import { DatabaseModule } from './database.module';
import { PhotoModule } from './photo/photo.module';
@Module({
imports: [
DatabaseModule.forRoot(),
PhotoModule,
],
imports: [DatabaseModule.forRoot(), PhotoModule],
})
export class AsyncApplicationModule {}

View File

@@ -5,7 +5,7 @@ import { Photo } from './photo/photo.entity';
@Module({})
export class DatabaseModule {
static async forRoot(): Promise<DynamicModule> {
await new Promise((resolve) => setTimeout(resolve, 1000));
await new Promise(resolve => setTimeout(resolve, 1000));
return {
module: DatabaseModule,
imports: [

View File

@@ -2,6 +2,6 @@ import { Module } from '@nestjs/common';
import { ApplicationGateway } from './app.gateway';
@Module({
providers: [ApplicationGateway]
providers: [ApplicationGateway],
})
export class ApplicationModule {}

View File

@@ -1,7 +1,7 @@
import { WebSocketGateway, SubscribeMessage } from '@nestjs/websockets';
@WebSocketGateway(8080, {
namespace: 'test'
namespace: 'test',
})
export class NamespaceGateway {
@SubscribeMessage('push')

View File

@@ -7,7 +7,7 @@
"test": "nyc --require ts-node/register mocha packages/**/*.spec.ts --reporter spec --retries 3 --require 'node_modules/reflect-metadata/Reflect.js'",
"integration-test": "mocha \"integration/*/{,!(node_modules)/**/}/*.spec.ts\" --reporter spec --require ts-node/register --require 'node_modules/reflect-metadata/Reflect.js'",
"lint": "tslint -p tsconfig.json -c tslint.json \"packages/**/*.ts\" -e \"*.spec.ts\"",
"format": "prettier **/**/*.ts --ignore-path ./.prettierignore --write && git status",
"format": "prettier \"**/*.ts\" --ignore-path ./.prettierignore --write && git status",
"clean": "gulp clean:bundle",
"prebuild": "rm -rf node_modules/@nestjs",
"build": "gulp build --dist node_modules/@nestjs",

View File

@@ -10,7 +10,6 @@ const metadataKeys = [
];
const validateKeys = (keys: string[]) => {
const validateKey = (key: string) => {
if (metadataKeys.includes(key)) {
return;

View File

@@ -5,5 +5,5 @@ export enum Transport {
MQTT,
GRPC,
RMQ,
KAFKA
KAFKA,
}

View File

@@ -1,4 +1,4 @@
import { isString, isObject } from '../utils/shared.utils';
import { isObject, isString } from '../utils/shared.utils';
/**
* Defines the base Nest HTTP exception, which is handled by the default
@@ -60,11 +60,11 @@ export class HttpException extends Error {
return isString(target) ? target : JSON.stringify(target);
}
public static createBody = (
public static createBody(
message: object | string,
error?: string,
statusCode?: number,
) => {
) {
if (!message) {
return { statusCode, error };
}

View File

@@ -37,7 +37,7 @@ export class ImATeapotException extends HttpException {
* @param message string or object describing the error condition.
* @param error HTTP response status code
*/
constructor(message?: string | object | any, error = 'I\'m a teapot') {
constructor(message?: string | object | any, error = `I'm a teapot`) {
super(
HttpException.createBody(message, error, HttpStatus.I_AM_A_TEAPOT),
HttpStatus.I_AM_A_TEAPOT,

View File

@@ -39,7 +39,11 @@ export class InternalServerErrorException extends HttpException {
error = 'Internal Server Error',
) {
super(
HttpException.createBody(message, error, HttpStatus.INTERNAL_SERVER_ERROR),
HttpException.createBody(
message,
error,
HttpStatus.INTERNAL_SERVER_ERROR,
),
HttpStatus.INTERNAL_SERVER_ERROR,
);
}

View File

@@ -4,7 +4,7 @@ import * as tls from 'tls';
import * as net from 'net';
export declare class Kafka {
constructor(config: KafkaConfig)
constructor(config: KafkaConfig);
producer(config?: ProducerConfig): Producer;
consumer(config?: ConsumerConfig): Consumer;
admin(config?: AdminConfig): Admin;
@@ -30,7 +30,7 @@ export type ISocketFactory = (
host: string,
port: number,
ssl: tls.ConnectionOptions,
onConnect: () => void
onConnect: () => void,
) => net.Socket;
export interface SASLOptions {
@@ -69,8 +69,8 @@ export type DefaultPartitioner = (args: PartitionerArgs) => number;
export type JavaCompatiblePartitioner = (args: PartitionerArgs) => number;
export let Partitioners: {
DefaultPartitioner: DefaultPartitioner
JavaCompatiblePartitioner: JavaCompatiblePartitioner
DefaultPartitioner: DefaultPartitioner;
JavaCompatiblePartitioner: JavaCompatiblePartitioner;
};
export interface PartitionMetadata {
@@ -109,9 +109,9 @@ export interface PartitionAssigner {
export interface CoordinatorMetadata {
errorCode: number;
coordinator: {
nodeId: number
host: string
port: number
nodeId: number;
host: string;
port: number;
};
}
@@ -125,34 +125,53 @@ export interface Cluster {
findBroker(node: { nodeId: string }): Promise<Broker>;
findControllerBroker(): Promise<Broker>;
findTopicPartitionMetadata(topic: string): PartitionMetadata[];
findLeaderForPartitions(topic: string, partitions: number[]): { [leader: string]: number[] };
findLeaderForPartitions(
topic: string,
partitions: number[],
): { [leader: string]: number[] };
findGroupCoordinator(group: { groupId: string }): Promise<Broker>;
findGroupCoordinatorMetadata(group: { groupId: string }): Promise<CoordinatorMetadata>;
findGroupCoordinatorMetadata(group: {
groupId: string;
}): Promise<CoordinatorMetadata>;
defaultOffset(config: { fromBeginning: boolean }): number;
fetchTopicsOffset(
topics: Array<{
topic: string
partitions: Array<{ partition: number }>
fromBeginning: boolean
}>
): Promise<{ topic: string; partitions: Array<{ partition: number; offset: string }> }>;
topic: string;
partitions: Array<{ partition: number }>;
fromBeginning: boolean;
}>,
): Promise<{
topic: string;
partitions: Array<{ partition: number; offset: string }>;
}>;
}
export interface Assignment { [topic: string]: number[]; }
export interface Assignment {
[topic: string]: number[];
}
export interface GroupMember { memberId: string; memberMetadata: MemberMetadata; }
export interface GroupMember {
memberId: string;
memberMetadata: MemberMetadata;
}
export interface GroupMemberAssignment { memberId: string; memberAssignment: Buffer; }
export interface GroupMemberAssignment {
memberId: string;
memberAssignment: Buffer;
}
export interface GroupState { name: string; metadata: Buffer; }
export interface GroupState {
name: string;
metadata: Buffer;
}
export interface Assigner {
name: string;
version: number;
assign(group: {
members: GroupMember[]
topics: string[]
userData: Buffer
members: GroupMember[];
topics: string[];
userData: Buffer;
}): Promise<GroupMemberAssignment[]>;
protocol(subscription: { topics: string[]; userData: Buffer }): GroupState;
}
@@ -215,11 +234,11 @@ export interface ConfigSynonyms {
export interface DescribeConfigResponse {
resources: {
configEntries: ConfigEntries[]
errorCode: number
errorMessage: string
resourceName: string
resourceType: ResourceType
configEntries: ConfigEntries[];
errorCode: number;
errorMessage: string;
resourceName: string;
resourceType: ResourceType;
}[];
throttleTime: number;
}
@@ -250,33 +269,33 @@ export interface InstrumentationEvent<T> {
export type ConnectEvent = InstrumentationEvent<null>;
export type DisconnectEvent = InstrumentationEvent<null>;
export type RequestEvent = InstrumentationEvent<{
apiKey: number
apiName: string
apiVersion: number
broker: string
clientId: string
correlationId: number
createdAt: number
duration: number
pendingDuration: number
sentAt: number
size: number
apiKey: number;
apiName: string;
apiVersion: number;
broker: string;
clientId: string;
correlationId: number;
createdAt: number;
duration: number;
pendingDuration: number;
sentAt: number;
size: number;
}>;
export type RequestTimeoutEvent = InstrumentationEvent<{
apiKey: number
apiName: string
apiVersion: number
broker: string
clientId: string
correlationId: number
createdAt: number
pendingDuration: number
sentAt: number
apiKey: number;
apiName: string;
apiVersion: number;
broker: string;
clientId: string;
correlationId: number;
createdAt: number;
pendingDuration: number;
sentAt: number;
}>;
export type RequestQueueSizeEvent = InstrumentationEvent<{
broker: string
clientId: string
queueSize: number
broker: string;
clientId: string;
queueSize: number;
}>;
export interface SeekEntry {
@@ -288,27 +307,44 @@ export interface Admin {
connect(): Promise<void>;
disconnect(): Promise<void>;
createTopics(options: {
validateOnly?: boolean
waitForLeaders?: boolean
timeout?: number
topics: ITopicConfig[]
validateOnly?: boolean;
waitForLeaders?: boolean;
timeout?: number;
topics: ITopicConfig[];
}): Promise<boolean>;
deleteTopics(options: { topics: string[]; timeout?: number }): Promise<void>;
fetchTopicMetadata(options: { topics: string[] }): Promise<{ topics: Array<ITopicMetadata> }>;
fetchTopicMetadata(options: {
topics: string[];
}): Promise<{ topics: Array<ITopicMetadata> }>;
fetchOffsets(options: {
groupId: string
topic: string
}): Promise<Array<{ partition: number; offset: string; metadata: string | null }>>;
groupId: string;
topic: string;
}): Promise<
Array<{ partition: number; offset: string; metadata: string | null }>
>;
fetchTopicOffsets(
topic: string
): Promise<Array<{ partition: number; offset: string; high: string; low: string }>>;
setOffsets(options: { groupId: string; topic: string; partitions: SeekEntry[] }): Promise<void>;
resetOffsets(options: { groupId: string; topic: string; earliest: boolean }): Promise<void>;
topic: string,
): Promise<
Array<{ partition: number; offset: string; high: string; low: string }>
>;
setOffsets(options: {
groupId: string;
topic: string;
partitions: SeekEntry[];
}): Promise<void>;
resetOffsets(options: {
groupId: string;
topic: string;
earliest: boolean;
}): Promise<void>;
describeConfigs(configs: {
resources: ResourceConfigQuery[]
includeSynonyms: boolean
resources: ResourceConfigQuery[];
includeSynonyms: boolean;
}): Promise<DescribeConfigResponse>;
alterConfigs(configs: { validateOnly: boolean; resources: IResourceConfig[] }): Promise<any>;
alterConfigs(configs: {
validateOnly: boolean;
resources: IResourceConfig[];
}): Promise<any>;
logger(): Logger;
on(eventName: ValueOf<AdminEvents>, listener: (...args: any[]) => void): void;
events: AdminEvents;
@@ -321,7 +357,8 @@ export interface ISerializer<T> {
decode(buffer: Buffer): T;
}
export interface MemberMetadata { version: number;
export interface MemberMetadata {
version: number;
topics: string[];
userData: Buffer;
}
@@ -333,8 +370,8 @@ export interface MemberAssignment {
}
export let AssignerProtocol: {
MemberMetadata: ISerializer<MemberMetadata>
MemberAssignment: ISerializer<MemberAssignment>
MemberMetadata: ISerializer<MemberMetadata>;
MemberAssignment: ISerializer<MemberAssignment>;
};
export enum logLevel {
@@ -366,23 +403,28 @@ export interface Broker {
isConnected(): boolean;
connect(): Promise<void>;
disconnect(): Promise<void>;
apiVersions(): Promise<{ [apiKey: number]: { minVersion: number; maxVersion: number } }>;
apiVersions(): Promise<{
[apiKey: number]: { minVersion: number; maxVersion: number };
}>;
metadata(
topics: string[]
topics: string[],
): Promise<{
brokers: Array<{ nodeId: number; host: string; port: number }>
brokers: Array<{ nodeId: number; host: string; port: number }>;
topicMetadata: Array<{
topicErrorCode: number
topic: number
partitionMetadata: PartitionMetadata[]
}>
topicErrorCode: number;
topic: number;
partitionMetadata: PartitionMetadata[];
}>;
}>;
offsetCommit(request: {
groupId: string
groupGenerationId: number
memberId: string
retentionTime?: number
topics: Array<{ topic: string; partitions: Array<{ partition: number; offset: string }> }>
groupId: string;
groupGenerationId: number;
memberId: string;
retentionTime?: number;
topics: Array<{
topic: string;
partitions: Array<{ partition: number; offset: string }>;
}>;
}): Promise<any>;
}
@@ -452,20 +494,23 @@ export interface ProducerEvents {
}
export type Producer = Sender & {
connect(): Promise<void>
disconnect(): Promise<void>
isIdempotent(): boolean
events: ProducerEvents
on(eventName: ValueOf<ProducerEvents>, listener: (...args: any[]) => void): void
transaction(): Promise<Transaction>
logger(): Logger
connect(): Promise<void>;
disconnect(): Promise<void>;
isIdempotent(): boolean;
events: ProducerEvents;
on(
eventName: ValueOf<ProducerEvents>,
listener: (...args: any[]) => void,
): void;
transaction(): Promise<Transaction>;
logger(): Logger;
};
export type Transaction = Sender & {
sendOffsets(offsets: Offsets & { consumerGroupId: string }): Promise<void>
commit(): Promise<void>
abort(): Promise<void>
isActive(): boolean
sendOffsets(offsets: Offsets & { consumerGroupId: string }): Promise<void>;
commit(): Promise<void>;
abort(): Promise<void>;
isActive(): boolean;
};
export interface ConsumerGroup {
@@ -491,7 +536,10 @@ export interface GroupDescription {
state: string;
}
export interface TopicPartitions { topic: string; partitions: number[]; }
export interface TopicPartitions {
topic: string;
partitions: number[];
}
export interface TopicPartitionOffsetAndMedata {
topic: string;
partition: number;
@@ -527,37 +575,37 @@ export interface ConsumerEvents {
REQUEST_QUEUE_SIZE: 'consumer.network.request_queue_size';
}
export type ConsumerHeartbeatEvent = InstrumentationEvent<{
groupId: string
memberId: string
groupGenerationId: number
groupId: string;
memberId: string;
groupGenerationId: number;
}>;
export type ConsumerCommitOffsetsEvent = InstrumentationEvent<{
groupId: string
memberId: string
groupGenerationId: number
groupId: string;
memberId: string;
groupGenerationId: number;
topics: {
topic: string
topic: string;
partitions: {
offset: string
partition: string
}[]
}[]
offset: string;
partition: string;
}[];
}[];
}>;
export interface IMemberAssignment {
[key: string]: number[];
}
export type ConsumerGroupJoinEvent = InstrumentationEvent<{
duration: number
groupId: string
isLeader: boolean
leaderId: string
groupProtocol: string
memberId: string
memberAssignment: IMemberAssignment
duration: number;
groupId: string;
isLeader: boolean;
leaderId: string;
groupProtocol: string;
memberId: string;
memberAssignment: IMemberAssignment;
}>;
export type ConsumerFetchEvent = InstrumentationEvent<{
numberOfBatches: number
duration: number
numberOfBatches: number;
duration: number;
}>;
interface IBatchProcessEvent {
topic: string;
@@ -569,13 +617,15 @@ interface IBatchProcessEvent {
firstOffset: string;
lastOffset: string;
}
export type ConsumerStartBatchProcessEvent = InstrumentationEvent<IBatchProcessEvent>;
export type ConsumerStartBatchProcessEvent = InstrumentationEvent<
IBatchProcessEvent
>;
export type ConsumerEndBatchProcessEvent = InstrumentationEvent<
IBatchProcessEvent & { duration: number }
>;
export type ConsumerCrashEvent = InstrumentationEvent<{
error: Error
groupId: string
error: Error;
groupId: string;
}>;
export interface OffsetsByTopicPartition {
@@ -613,23 +663,35 @@ export type ConsumerEachBatchPayload = EachBatchPayload;
export interface Consumer {
connect(): Promise<void>;
disconnect(): Promise<void>;
subscribe(topic: { topic: string | RegExp; fromBeginning?: boolean }): Promise<void>;
subscribe(topic: {
topic: string | RegExp;
fromBeginning?: boolean;
}): Promise<void>;
stop(): Promise<void>;
run(config?: {
autoCommit?: boolean
autoCommitInterval?: number | null
autoCommitThreshold?: number | null
eachBatchAutoResolve?: boolean
partitionsConsumedConcurrently?: number
eachBatch?: (payload: EachBatchPayload) => Promise<void>
eachMessage?: (payload: EachMessagePayload) => Promise<void>
autoCommit?: boolean;
autoCommitInterval?: number | null;
autoCommitThreshold?: number | null;
eachBatchAutoResolve?: boolean;
partitionsConsumedConcurrently?: number;
eachBatch?: (payload: EachBatchPayload) => Promise<void>;
eachMessage?: (payload: EachMessagePayload) => Promise<void>;
}): Promise<void>;
commitOffsets(topicPartitions: Array<TopicPartitionOffsetAndMedata>): Promise<void>;
seek(topicPartition: { topic: string; partition: number; offset: string }): void;
commitOffsets(
topicPartitions: Array<TopicPartitionOffsetAndMedata>,
): Promise<void>;
seek(topicPartition: {
topic: string;
partition: number;
offset: string;
}): void;
describeGroup(): Promise<GroupDescription>;
pause(topics: Array<{ topic: string; partitions?: number[] }>): void;
resume(topics: Array<{ topic: string; partitions?: number[] }>): void;
on(eventName: ValueOf<ConsumerEvents>, listener: (...args: any[]) => void): void;
on(
eventName: ValueOf<ConsumerEvents>,
listener: (...args: any[]) => void,
): void;
logger(): Logger;
events: ConsumerEvents;
}
@@ -643,8 +705,8 @@ export enum CompressionTypes {
}
export let CompressionCodecs: {
[CompressionTypes.GZIP]: () => any
[CompressionTypes.Snappy]: () => any
[CompressionTypes.LZ4]: () => any
[CompressionTypes.ZSTD]: () => any
[CompressionTypes.GZIP]: () => any;
[CompressionTypes.Snappy]: () => any;
[CompressionTypes.LZ4]: () => any;
[CompressionTypes.ZSTD]: () => any;
};

View File

@@ -88,11 +88,7 @@ export interface MqttClientOptions extends ISecureClientOptions {
*/
retain: boolean;
};
transformWsUrl?: (
url: string,
options: any,
client: any,
) => string;
transformWsUrl?: (url: string, options: any, client: any) => string;
}
export interface ISecureClientOptions {
/**

View File

@@ -4,7 +4,7 @@ import {
NatsOptions,
MqttOptions,
GrpcOptions,
RmqOptions
RmqOptions,
} from './microservice-configuration.interface';
export interface ClientOptions {

View File

@@ -1,6 +1,11 @@
import { Transport } from '../../enums/transport.enum';
import { MqttClientOptions } from '../external/mqtt-options.interface';
import { KafkaConfig, ConsumerConfig, ProducerConfig, CompressionTypes } from '../external/kafka-options.interface';
import {
KafkaConfig,
ConsumerConfig,
ProducerConfig,
CompressionTypes,
} from '../external/kafka-options.interface';
import { CustomTransportStrategy } from './custom-transport-strategy.interface';
import { Deserializer } from './deserializer.interface';
import { Serializer } from './serializer.interface';
@@ -111,21 +116,21 @@ export interface RmqOptions {
export interface KafkaOptions {
transport?: Transport.KAFKA;
options?: {
client?: KafkaConfig,
consumer?: ConsumerConfig,
client?: KafkaConfig;
consumer?: ConsumerConfig;
run?: {
autoCommit?: boolean
autoCommitInterval?: number | null
autoCommitThreshold?: number | null
eachBatchAutoResolve?: boolean
partitionsConsumedConcurrently?: number
},
producer?: ProducerConfig,
autoCommit?: boolean;
autoCommitInterval?: number | null;
autoCommitThreshold?: number | null;
eachBatchAutoResolve?: boolean;
partitionsConsumedConcurrently?: number;
};
producer?: ProducerConfig;
send?: {
acks?: number;
timeout?: number;
compression?: CompressionTypes;
}
};
serializer?: Serializer;
deserializer?: Deserializer;
};

View File

@@ -4,11 +4,7 @@ import { Inject, Injectable } from '../decorators/core';
import { ClassTransformOptions } from '../interfaces/external/class-transform-options.interface';
import { loadPackage } from '../utils/load-package.util';
import { isObject } from '../utils/shared.utils';
import {
CallHandler,
ExecutionContext,
NestInterceptor,
} from '../interfaces';
import { CallHandler, ExecutionContext, NestInterceptor } from '../interfaces';
import { CLASS_SERIALIZER_OPTIONS } from './class-serializer.constants';
let classTransformer: any = {};

View File

@@ -92,17 +92,11 @@ describe('createParamDecorator', () => {
describe('when class type passed as data', () => {
class Data {}
class Test {
public test(
@Decorator(Data) prop,
) { }
public test(@Decorator(Data) prop) {}
}
it('should return class type as data parameter', () => {
const metadata = Reflect.getMetadata(
ROUTE_ARGS_METADATA,
Test,
'test',
);
const metadata = Reflect.getMetadata(ROUTE_ARGS_METADATA, Test, 'test');
const key = Object.keys(metadata)[0];
expect(metadata[key].data).to.equal(Data);
});

View File

@@ -34,8 +34,7 @@ describe('@UseFilters', () => {
it('when object is invalid should throw exception', () => {
try {
UseFilters('test' as any)({});
}
catch (e) {
} catch (e) {
expect(e).to.be.instanceof(InvalidDecoratorItemException);
}
});

View File

@@ -31,8 +31,7 @@ describe('@UsePipes', () => {
it('when object is invalid should throw exception', () => {
try {
UsePipes('test' as any)({});
}
catch (e) {
} catch (e) {
expect(e).to.be.instanceof(InvalidDecoratorItemException);
}
});

View File

@@ -1,10 +1,16 @@
import { expect } from 'chai';
import { BadRequestException, HttpException, NotFoundException } from '../../exceptions';
import {
BadRequestException,
HttpException,
NotFoundException,
} from '../../exceptions';
describe('HttpException', () => {
it('should return a message as a string when input is a string', () => {
const message: string = 'My error message';
expect(new HttpException(message, 404).message).to.be.eql('My error message');
expect(new HttpException(message, 404).message).to.be.eql(
'My error message',
);
});
it('should return a message as an object when input is an object', () => {
@@ -26,7 +32,10 @@ describe('HttpException', () => {
});
it('should return an object even when the message is undefined', () => {
expect(new BadRequestException().message).to.be.eql({ statusCode: 400, error: 'Bad Request' });
expect(new BadRequestException().message).to.be.eql({
statusCode: 400,
error: 'Bad Request',
});
});
it('should return a status code', () => {
@@ -111,5 +120,4 @@ describe('HttpException', () => {
});
});
});
});

View File

@@ -19,7 +19,8 @@ describe('ParseIntPipe', () => {
});
describe('when validation fails', () => {
it('should throw an error', async () => {
return expect(target.transform('123abc', {} as ArgumentMetadata)).to.be.rejected;
return expect(target.transform('123abc', {} as ArgumentMetadata)).to.be
.rejected;
});
});
});

View File

@@ -174,7 +174,7 @@ describe('ValidationPipe', () => {
});
});
});
describe('when validation doesn\'t transform', () => {
describe("when validation doesn't transform", () => {
describe('when validation strips', () => {
it('should return a plain object without extra properties', async () => {
target = new ValidationPipe({ transform: false, whitelist: true });

View File

@@ -8,7 +8,7 @@ import {
validatePath,
isNil,
isEmpty,
isPlainObject
isPlainObject,
} from '../../utils/shared.utils';
function Foo(a) {
@@ -47,9 +47,11 @@ describe('Shared utils', () => {
it('should returns true when obj is plain object', () => {
expect(isPlainObject({})).to.be.true;
expect(isPlainObject({ prop: true })).to.be.true;
expect(isPlainObject({
constructor: Foo
})).to.be.true;
expect(
isPlainObject({
constructor: Foo,
}),
).to.be.true;
expect(isPlainObject(Object.create(null))).to.be.true;
});
it('should returns false when object is not object', () => {

View File

@@ -9,6 +9,8 @@ export class UndefinedDependencyException extends RuntimeException {
undefinedDependencyContext: InjectorDependencyContext,
module?: Module,
) {
super(UNKNOWN_DEPENDENCIES_MESSAGE(type, undefinedDependencyContext, module));
super(
UNKNOWN_DEPENDENCIES_MESSAGE(type, undefinedDependencyContext, module),
);
}
}

View File

@@ -3,7 +3,8 @@ import { RuntimeException } from './runtime.exception';
export class UnknownElementException extends RuntimeException {
constructor(name?: string) {
super(
`Nest could not find ${name || 'given'} element (this provider does not exist in the current context)`,
`Nest could not find ${name ||
'given'} element (this provider does not exist in the current context)`,
);
}
}

View File

@@ -16,9 +16,7 @@ import {
function hasOnAppShutdownHook(
instance: unknown,
): instance is OnApplicationShutdown {
return !isNil(
(instance as OnApplicationShutdown).onApplicationShutdown,
);
return !isNil((instance as OnApplicationShutdown).onApplicationShutdown);
}
/**

View File

@@ -38,5 +38,4 @@ export class ModuleCompiler {
): module is DynamicModule {
return !!(module as DynamicModule).module;
}
}

View File

@@ -23,7 +23,7 @@ export function getTransientInstances(
* @param instances The instances which should be checked whether they are transcient
*/
export function getNonTransientInstances(
instances: [string, InstanceWrapper][]
instances: [string, InstanceWrapper][],
): InstanceWrapper[] {
return iterate(instances)
.filter(

View File

@@ -1,7 +1,11 @@
import { RequestMethod } from '@nestjs/common';
import { PATH_METADATA } from '@nestjs/common/constants';
import { RouteInfo, Type } from '@nestjs/common/interfaces';
import { isString, isUndefined, validatePath } from '@nestjs/common/utils/shared.utils';
import {
isString,
isUndefined,
validatePath,
} from '@nestjs/common/utils/shared.utils';
import { NestContainer } from '../injector/container';
import { MetadataScanner } from '../metadata-scanner';
import { RouterExplorer } from '../router/router-explorer';
@@ -37,11 +41,19 @@ export class RoutesMapper {
Object.create(route),
route.prototype,
);
const concatPaths = <T>(acc: T[], currentValue: T[]) => acc.concat(currentValue);
return paths.map(item => item.path && item.path.map(p => ({
path: this.validateGlobalPath(routePath) + this.validateRoutePath(p),
const concatPaths = <T>(acc: T[], currentValue: T[]) =>
acc.concat(currentValue);
return paths
.map(
item =>
item.path &&
item.path.map(p => ({
path:
this.validateGlobalPath(routePath) + this.validateRoutePath(p),
method: item.requestMethod,
}))).reduce(concatPaths, []);
})),
)
.reduce(concatPaths, []);
}
private isRouteInfo(

View File

@@ -40,7 +40,9 @@ describe('ExceptionsHandler', () => {
if (isNil(body)) {
return responseRef.send();
}
return isObject(body) ? responseRef.json(body) : responseRef.send(String(body));
return isObject(body)
? responseRef.json(body)
: responseRef.send(String(body));
});
});
it('should method send expected response status code and message when exception is unknown', () => {

View File

@@ -50,9 +50,7 @@ describe('GuardsConsumer', () => {
describe('pickResult', () => {
describe('when result is Observable', () => {
it('should returns result', async () => {
expect(
await consumer.pickResult(of(true)),
).to.be.true;
expect(await consumer.pickResult(of(true))).to.be.true;
});
});
describe('when result is Promise', () => {

View File

@@ -69,7 +69,7 @@ describe('ModuleTokenFactory', () => {
class Provider {}
const metadata = { providers: [Provider], exports: [Provider] };
expect(factory.getDynamicMetadataToken(metadata)).to.be.eql(
'{"providers":["Provider"],"exports":["Provider"]}'
'{"providers":["Provider"],"exports":["Provider"]}',
);
});
});

View File

@@ -4,8 +4,8 @@ import { HttpException } from '../../../common/exceptions/http.exception';
import { ExceptionsHandler } from '../../exceptions/exceptions-handler';
import { RouterProxy } from '../../router/router-proxy';
import { NoopHttpAdapter } from '../utils/noop-adapter.spec';
import {SinonSpy} from "sinon";
import {ExecutionContextHost} from "../../helpers/execution-context-host";
import { SinonSpy } from 'sinon';
import { ExecutionContextHost } from '../../helpers/execution-context-host';
describe('RouterProxy', () => {
let routerProxy: RouterProxy;
@@ -31,7 +31,12 @@ describe('RouterProxy', () => {
proxy(null, null, null);
expect(nextStub.calledOnce).to.be.true;
expect(nextStub.calledWith(httpException, new ExecutionContextHost([null, null, null]))).to.be.true;
expect(
nextStub.calledWith(
httpException,
new ExecutionContextHost([null, null, null]),
),
).to.be.true;
});
it('should method encapsulate async callback passed as argument', done => {
@@ -42,7 +47,12 @@ describe('RouterProxy', () => {
setTimeout(() => {
expect(nextStub.calledOnce).to.be.true;
expect(nextStub.calledWith(httpException, new ExecutionContextHost([null, null, null]))).to.be.true;
expect(
nextStub.calledWith(
httpException,
new ExecutionContextHost([null, null, null]),
),
).to.be.true;
done();
}, 0);
});
@@ -64,7 +74,12 @@ describe('RouterProxy', () => {
proxy(null, null, null, null);
expect(nextStub.calledOnce).to.be.true;
expect(nextStub.calledWith(httpException, new ExecutionContextHost([null, null, null]))).to.be.true;
expect(
nextStub.calledWith(
httpException,
new ExecutionContextHost([null, null, null]),
),
).to.be.true;
});
it('should method encapsulate async callback passed as argument', done => {
@@ -78,7 +93,12 @@ describe('RouterProxy', () => {
setTimeout(() => {
expect(nextStub.calledOnce).to.be.true;
expect(nextStub.calledWith(httpException, new ExecutionContextHost([null, null, null]))).to.be.true;
expect(
nextStub.calledWith(
httpException,
new ExecutionContextHost([null, null, null]),
),
).to.be.true;
done();
}, 0);
});

View File

@@ -10,7 +10,7 @@ import {
MqttOptions,
NatsOptions,
RedisOptions,
RmqOptions
RmqOptions,
} from '../interfaces/microservice-configuration.interface';
import { ClientGrpcProxy } from './client-grpc';
import { ClientKafka } from './client-kafka';

View File

@@ -98,7 +98,9 @@ export class ClientRMQ extends ClientProxy {
public createClient<T = any>(): T {
const socketOptions = this.getOptionsProp(this.options, 'socketOptions');
return rqmPackage.connect(this.urls, { connectionOptions: socketOptions }) as T;
return rqmPackage.connect(this.urls, {
connectionOptions: socketOptions,
}) as T;
}
public mergeDisconnectEvent<T = any>(

View File

@@ -1,4 +1,4 @@
export enum PatternHandler {
MESSAGE = 1,
EVENT = 2
EVENT = 2,
}

View File

@@ -5,5 +5,5 @@ export enum Transport {
MQTT,
GRPC,
RMQ,
KAFKA
KAFKA,
}

View File

@@ -38,11 +38,7 @@ export declare class Client extends EventEmitter {
* ommitted, even with a callback. The Subscriber Id is returned.
*/
subscribe(subject: string, callback: Function): number;
subscribe(
subject: string,
opts: any,
callback: Function,
): number;
subscribe(subject: string, opts: any, callback: Function): number;
/**
* Unsubscribe to a given Subscriber Id, with optional max parameter.

View File

@@ -6,7 +6,7 @@ import {
MqttOptions,
NatsOptions,
RedisOptions,
RmqOptions
RmqOptions,
} from './microservice-configuration.interface';
import { Serializer } from './serializer.interface';

View File

@@ -1,5 +1,10 @@
import { MqttClientOptions } from '@nestjs/common/interfaces/external/mqtt-options.interface';
import { KafkaConfig, ConsumerConfig, ProducerConfig, CompressionTypes } from '@nestjs/common/interfaces/external/kafka-options.interface';
import {
KafkaConfig,
ConsumerConfig,
ProducerConfig,
CompressionTypes,
} from '@nestjs/common/interfaces/external/kafka-options.interface';
import { Transport } from '../enums/transport.enum';
import { Server } from '../server/server';
import { CustomTransportStrategy } from './custom-transport-strategy.interface';

View File

@@ -1,4 +1,3 @@
export type MsFundamentalPattern = string | number;
export interface MsObjectPattern {

View File

@@ -37,7 +37,7 @@ describe('ClientProxyFactory', () => {
transport: Transport.GRPC,
options: {
protoPath: join(__dirname, './test.proto'),
package: 'test'
package: 'test',
},
});
expect(proxy instanceof ClientGrpcProxy).to.be.true;

View File

@@ -185,7 +185,6 @@ describe('ClientProxy', function() {
Utils,
'transformPatternToRoute',
);
(client as any).normalizePattern(inputPattern);
expect(msvcUtilTransformPatternToRouteStub.args[0][0]).to.be.equal(

View File

@@ -108,8 +108,8 @@ describe('RpcExceptionsHandler', () => {
expect(funcSpy.calledWith(exception)).to.be.true;
});
it('should returns stream', () => {
expect(handler.invokeCustomFilters(new TestException(), null)).to.be.not
.null;
expect(handler.invokeCustomFilters(new TestException(), null)).to.be
.not.null;
});
});
describe('when filter does not exists in filters array', () => {
@@ -118,7 +118,8 @@ describe('RpcExceptionsHandler', () => {
expect(funcSpy.notCalled).to.be.true;
});
it('should returns null', () => {
expect(handler.invokeCustomFilters(new TestException(), null)).to.be.null;
expect(handler.invokeCustomFilters(new TestException(), null)).to.be
.null;
});
});
});

View File

@@ -24,19 +24,19 @@ export const longPayload = [
friends: [
{
id: 0,
name: 'Cecelia James'
name: 'Cecelia James',
},
{
id: 1,
name: 'Hilary Young'
name: 'Hilary Young',
},
{
id: 2,
name: 'Sharron Goodwin'
}
name: 'Sharron Goodwin',
},
],
greeting: 'Hello, Watson Aguilar! You have 3 unread messages.',
favoriteFruit: 'banana'
favoriteFruit: 'banana',
},
{
_id: '584f1714b2e945fb30f73892',
@@ -65,24 +65,24 @@ export const longPayload = [
'officia',
'minim',
'cupidatat',
'adipisicing'
'adipisicing',
],
friends: [
{
id: 0,
name: 'Olson Mccall'
name: 'Olson Mccall',
},
{
id: 1,
name: 'Carolina Conway'
name: 'Carolina Conway',
},
{
id: 2,
name: 'Carlson Pacheco'
}
name: 'Carlson Pacheco',
},
],
greeting: 'Hello, Aguirre Salazar! You have 9 unread messages.',
favoriteFruit: 'apple'
favoriteFruit: 'apple',
},
{
_id: '584f17148282bb876fc4e9a2',
@@ -108,19 +108,19 @@ export const longPayload = [
friends: [
{
id: 0,
name: 'Lesley Velasquez'
name: 'Lesley Velasquez',
},
{
id: 1,
name: 'Natasha Simmons'
name: 'Natasha Simmons',
},
{
id: 2,
name: 'Isabel Avery'
}
name: 'Isabel Avery',
},
],
greeting: 'Hello, Hardin Grant! You have 7 unread messages.',
favoriteFruit: 'strawberry'
favoriteFruit: 'strawberry',
},
{
_id: '584f1714d90ff4b8914a69e7',
@@ -149,24 +149,24 @@ export const longPayload = [
'amet',
'nulla',
'consequat',
'nisi'
'nisi',
],
friends: [
{
id: 0,
name: 'Barron Maynard'
name: 'Barron Maynard',
},
{
id: 1,
name: 'Lynn Shepard'
name: 'Lynn Shepard',
},
{
id: 2,
name: 'Robin Whitehead'
}
name: 'Robin Whitehead',
},
],
greeting: 'Hello, Randall Roy! You have 3 unread messages.',
favoriteFruit: 'strawberry'
favoriteFruit: 'strawberry',
},
{
_id: '584f17142a8f47cef0f5401a',
@@ -195,24 +195,24 @@ export const longPayload = [
'incididunt',
'officia',
'amet',
'irure'
'irure',
],
friends: [
{
id: 0,
name: 'Mckee Norton'
name: 'Mckee Norton',
},
{
id: 1,
name: 'Durham Parrish'
name: 'Durham Parrish',
},
{
id: 2,
name: 'Stewart Kramer'
}
name: 'Stewart Kramer',
},
],
greeting: 'Hello, Chandler Vasquez! You have 3 unread messages.',
favoriteFruit: 'strawberry'
favoriteFruit: 'strawberry',
},
{
_id: '584f171450a4e9dda687adc5',
@@ -241,23 +241,23 @@ export const longPayload = [
'ut',
'proident',
'aliquip',
'labore'
'labore',
],
friends: [
{
id: 0,
name: 'Adela Preston'
name: 'Adela Preston',
},
{
id: 1,
name: 'Phillips Moses'
name: 'Phillips Moses',
},
{
id: 2,
name: 'Neva Wise'
}
name: 'Neva Wise',
},
],
greeting: 'Hello, Fernandez Caldwell! You have 10 unread messages.',
favoriteFruit: 'apple'
}
favoriteFruit: 'apple',
},
];

View File

@@ -51,7 +51,8 @@ describe('ServerFactory', () => {
it(`should return kafka server`, () => {
expect(
ServerFactory.create({ transport: Transport.KAFKA }) instanceof ServerKafka,
ServerFactory.create({ transport: Transport.KAFKA }) instanceof
ServerKafka,
).to.be.true;
});

View File

@@ -82,7 +82,6 @@ describe('ServerGrpc', () => {
test2: { service: true },
}));
sinon.stub(server, 'getServiceNames').callsFake(() => serviceNames);
(server as any).grpcClient = { addService: sinon.spy() };
await server.bindEvents();
@@ -131,7 +130,6 @@ describe('ServerGrpc', () => {
const spy = sinon
.stub(server, 'createServiceMethod')
.callsFake(() => ({} as any));
(server as any).messageHandlers = handlers;
await server.createService(
{
@@ -154,7 +152,6 @@ describe('ServerGrpc', () => {
.returns('test2');
sinon.stub(server, 'createServiceMethod').callsFake(() => ({} as any));
(server as any).messageHandlers = handlers;
await server.createService(
{
@@ -190,7 +187,6 @@ describe('ServerGrpc', () => {
.returns('test2');
sinon.stub(server, 'createServiceMethod').callsFake(() => ({} as any));
(server as any).messageHandlers = handlers;
await server.createService(
{

View File

@@ -60,7 +60,6 @@ describe('Server', () => {
it(`should call 'transformPatternToRoute' with 'string' argument`, () => {
const inputServerPattern = 'hello';
const transformedServerPattern = inputServerPattern;
(server as any).getRouteFromPattern(inputServerPattern);
expect(msvcUtilTransformPatternToRouteStub.args[0][0]).to.be.equal(
@@ -76,7 +75,6 @@ describe('Server', () => {
controller: 'app',
use: 'getHello',
};
(server as any).getRouteFromPattern(inputServerPattern);
expect(msvcUtilTransformPatternToRouteStub.args[0][0]).to.be.deep.equal(

View File

@@ -40,17 +40,13 @@ export function AnyFilesInterceptor(
const ctx = context.switchToHttp();
await new Promise((resolve, reject) =>
this.multer.any()(
ctx.getRequest(),
ctx.getResponse(),
(err: any) => {
this.multer.any()(ctx.getRequest(), ctx.getResponse(), (err: any) => {
if (err) {
const error = transformException(err);
return reject(error);
}
resolve();
},
),
}),
);
return next.handle();
}

View File

@@ -34,7 +34,6 @@ describe('FilesInterceptor', () => {
const target = new (AnyFilesInterceptor())();
const err = {};
const callback = (req, res, next) => next(err);
(target as any).multer = {
any: () => callback,
};

View File

@@ -53,7 +53,6 @@ describe('FileFieldsInterceptor', () => {
const target = new (FileFieldsInterceptor(argument))();
const err = {};
const callback = (req, res, next) => next(err);
(target as any).fields = {
array: () => callback,
};

View File

@@ -35,7 +35,6 @@ describe('FileInterceptor', () => {
const target = new (FileInterceptor(fieldName))();
const err = {};
const callback = (req, res, next) => next(err);
(target as any).multer = {
single: () => callback,
};

View File

@@ -37,7 +37,6 @@ describe('FilesInterceptor', () => {
const target = new (FilesInterceptor(fieldName))();
const err = {};
const callback = (req, res, next) => next(err);
(target as any).multer = {
array: () => callback,
};

View File

@@ -3,9 +3,7 @@ import { MESSAGE_MAPPING_METADATA, MESSAGE_METADATA } from '../constants';
/**
* Subscribes to messages that fulfils chosen pattern.
*/
export const SubscribeMessage = <T = string>(
message: T,
): MethodDecorator => {
export const SubscribeMessage = <T = string>(message: T): MethodDecorator => {
return (target, key, descriptor: PropertyDescriptor) => {
Reflect.defineMetadata(MESSAGE_MAPPING_METADATA, true, descriptor.value);
Reflect.defineMetadata(MESSAGE_METADATA, message, descriptor.value);

View File

@@ -106,7 +106,6 @@ describe('WebSocketsController', () => {
hookServerToProperties = sinon.spy();
subscribeEvents = sinon.spy();
(instance as any).hookServerToProperties = hookServerToProperties;
(instance as any).subscribeEvents = subscribeEvents;
});
@@ -150,7 +149,6 @@ describe('WebSocketsController', () => {
disconnect: {},
connection: {},
};
(instance as any).subscribeInitEvent = subscribeInitEvent;
(instance as any).getConnectionHandler = getConnectionHandler;
(instance as any).subscribeConnectionEvent = subscribeConnectionEvent;

View File

@@ -1,4 +1,9 @@
import { BadRequestException, PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
import {
BadRequestException,
PipeTransform,
Injectable,
ArgumentMetadata,
} from '@nestjs/common';
@Injectable()
export class ParseIntPipe implements PipeTransform<string> {

View File

@@ -1,4 +1,3 @@
/** ------------------------------------------------------
* THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY)
* -------------------------------------------------------

View File

@@ -1,8 +1,4 @@
import {
CacheInterceptor,
ExecutionContext,
Injectable,
} from '@nestjs/common';
import { CacheInterceptor, ExecutionContext, Injectable } from '@nestjs/common';
@Injectable()
class HttpCacheInterceptor extends CacheInterceptor {

View File

@@ -1,22 +1,22 @@
export enum MutationType {
CREATED = "CREATED",
UPDATED = "UPDATED",
DELETED = "DELETED"
CREATED = 'CREATED',
UPDATED = 'UPDATED',
DELETED = 'DELETED',
}
export enum PostOrderByInput {
id_ASC = "id_ASC",
id_DESC = "id_DESC",
isPublished_ASC = "isPublished_ASC",
isPublished_DESC = "isPublished_DESC",
title_ASC = "title_ASC",
title_DESC = "title_DESC",
text_ASC = "text_ASC",
text_DESC = "text_DESC",
updatedAt_ASC = "updatedAt_ASC",
updatedAt_DESC = "updatedAt_DESC",
createdAt_ASC = "createdAt_ASC",
createdAt_DESC = "createdAt_DESC"
id_ASC = 'id_ASC',
id_DESC = 'id_DESC',
isPublished_ASC = 'isPublished_ASC',
isPublished_DESC = 'isPublished_DESC',
title_ASC = 'title_ASC',
title_DESC = 'title_DESC',
text_ASC = 'text_ASC',
text_DESC = 'text_DESC',
updatedAt_ASC = 'updatedAt_ASC',
updatedAt_DESC = 'updatedAt_DESC',
createdAt_ASC = 'createdAt_ASC',
createdAt_DESC = 'createdAt_DESC',
}
export class PostCreateInput {
@@ -110,11 +110,23 @@ export class BatchPayload {
export abstract class IMutation {
abstract createPost(data: PostCreateInput): Post | Promise<Post>;
abstract updatePost(data: PostUpdateInput, where: PostWhereUniqueInput): Post | Promise<Post>;
abstract updatePost(
data: PostUpdateInput,
where: PostWhereUniqueInput,
): Post | Promise<Post>;
abstract deletePost(where: PostWhereUniqueInput): Post | Promise<Post>;
abstract upsertPost(where: PostWhereUniqueInput, create: PostCreateInput, update: PostUpdateInput): Post | Promise<Post>;
abstract updateManyPosts(data: PostUpdateInput, where?: PostWhereInput): BatchPayload | Promise<BatchPayload>;
abstract deleteManyPosts(where?: PostWhereInput): BatchPayload | Promise<BatchPayload>;
abstract upsertPost(
where: PostWhereUniqueInput,
create: PostCreateInput,
update: PostUpdateInput,
): Post | Promise<Post>;
abstract updateManyPosts(
data: PostUpdateInput,
where?: PostWhereInput,
): BatchPayload | Promise<BatchPayload>;
abstract deleteManyPosts(
where?: PostWhereInput,
): BatchPayload | Promise<BatchPayload>;
}
export class PageInfo {
@@ -157,15 +169,33 @@ export class PostSubscriptionPayload {
}
export abstract class IQuery {
abstract posts(where?: PostWhereInput, orderBy?: PostOrderByInput, skip?: number, after?: string, before?: string, first?: number, last?: number): Post[] | Promise<Post[]>;
abstract posts(
where?: PostWhereInput,
orderBy?: PostOrderByInput,
skip?: number,
after?: string,
before?: string,
first?: number,
last?: number,
): Post[] | Promise<Post[]>;
abstract post(where: PostWhereUniqueInput): Post | Promise<Post>;
abstract postsConnection(where?: PostWhereInput, orderBy?: PostOrderByInput, skip?: number, after?: string, before?: string, first?: number, last?: number): PostConnection | Promise<PostConnection>;
abstract postsConnection(
where?: PostWhereInput,
orderBy?: PostOrderByInput,
skip?: number,
after?: string,
before?: string,
first?: number,
last?: number,
): PostConnection | Promise<PostConnection>;
abstract node(id: string): Node | Promise<Node>;
abstract temp__(): boolean | Promise<boolean>;
}
export abstract class ISubscription {
abstract post(where?: PostSubscriptionWhereInput): PostSubscriptionPayload | Promise<PostSubscriptionPayload>;
abstract post(
where?: PostSubscriptionWhereInput,
): PostSubscriptionPayload | Promise<PostSubscriptionPayload>;
}
export type Long = any;

View File

@@ -1,49 +1,127 @@
import { GraphQLResolveInfo, GraphQLSchema } from 'graphql'
import { IResolvers } from 'graphql-tools/dist/Interfaces'
import { Options } from 'graphql-binding'
import { makePrismaBindingClass, BasePrismaOptions } from 'prisma-binding'
import { GraphQLResolveInfo, GraphQLSchema } from 'graphql';
import { IResolvers } from 'graphql-tools/dist/Interfaces';
import { Options } from 'graphql-binding';
import { makePrismaBindingClass, BasePrismaOptions } from 'prisma-binding';
export interface Query {
posts: <T = Post[]>(args: { where?: PostWhereInput, orderBy?: PostOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
post: <T = Post | null>(args: { where: PostWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
postsConnection: <T = PostConnection>(args: { where?: PostWhereInput, orderBy?: PostOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
node: <T = Node | null>(args: { id: ID_Output }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T>
posts: <T = Post[]>(
args: {
where?: PostWhereInput;
orderBy?: PostOrderByInput;
skip?: Int;
after?: String;
before?: String;
first?: Int;
last?: Int;
},
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
post: <T = Post | null>(
args: { where: PostWhereUniqueInput },
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
postsConnection: <T = PostConnection>(
args: {
where?: PostWhereInput;
orderBy?: PostOrderByInput;
skip?: Int;
after?: String;
before?: String;
first?: Int;
last?: Int;
},
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
node: <T = Node | null>(
args: { id: ID_Output },
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
}
export interface Mutation {
createPost: <T = Post>(args: { data: PostCreateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
updatePost: <T = Post | null>(args: { data: PostUpdateInput, where: PostWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
deletePost: <T = Post | null>(args: { where: PostWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
upsertPost: <T = Post>(args: { where: PostWhereUniqueInput, create: PostCreateInput, update: PostUpdateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
updateManyPosts: <T = BatchPayload>(args: { data: PostUpdateInput, where?: PostWhereInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> ,
deleteManyPosts: <T = BatchPayload>(args: { where?: PostWhereInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T>
createPost: <T = Post>(
args: { data: PostCreateInput },
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
updatePost: <T = Post | null>(
args: { data: PostUpdateInput; where: PostWhereUniqueInput },
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
deletePost: <T = Post | null>(
args: { where: PostWhereUniqueInput },
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
upsertPost: <T = Post>(
args: {
where: PostWhereUniqueInput;
create: PostCreateInput;
update: PostUpdateInput;
},
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
updateManyPosts: <T = BatchPayload>(
args: { data: PostUpdateInput; where?: PostWhereInput },
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
deleteManyPosts: <T = BatchPayload>(
args: { where?: PostWhereInput },
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<T>;
}
export interface Subscription {
post: <T = PostSubscriptionPayload | null>(args: { where?: PostSubscriptionWhereInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<AsyncIterator<T>>
post: <T = PostSubscriptionPayload | null>(
args: { where?: PostSubscriptionWhereInput },
info?: GraphQLResolveInfo | string,
options?: Options,
) => Promise<AsyncIterator<T>>;
}
export interface Exists {
Post: (where?: PostWhereInput) => Promise<boolean>
Post: (where?: PostWhereInput) => Promise<boolean>;
}
export interface Prisma {
query: Query
mutation: Mutation
subscription: Subscription
exists: Exists
request: <T = any>(query: string, variables?: {[key: string]: any}) => Promise<T>
delegate(operation: 'query' | 'mutation', fieldName: string, args: {
query: Query;
mutation: Mutation;
subscription: Subscription;
exists: Exists;
request: <T = any>(
query: string,
variables?: { [key: string]: any },
) => Promise<T>;
delegate(
operation: 'query' | 'mutation',
fieldName: string,
args: {
[key: string]: any;
}, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<any>;
delegateSubscription(fieldName: string, args?: {
},
infoOrQuery?: GraphQLResolveInfo | string,
options?: Options,
): Promise<any>;
delegateSubscription(
fieldName: string,
args?: {
[key: string]: any;
}, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<AsyncIterator<any>>;
},
infoOrQuery?: GraphQLResolveInfo | string,
options?: Options,
): Promise<AsyncIterator<any>>;
getAbstractResolvers(filterSchema?: GraphQLSchema | string): IResolvers;
}
export interface BindingConstructor<T> {
new(options: BasePrismaOptions): T
new (options: BasePrismaOptions): T;
}
/**
* Type Defs
@@ -353,106 +431,107 @@ type Query {
type Subscription {
post(where: PostSubscriptionWhereInput): PostSubscriptionPayload
}
`
`;
export const Prisma = makePrismaBindingClass<BindingConstructor<Prisma>>({typeDefs})
export const Prisma = makePrismaBindingClass<BindingConstructor<Prisma>>({
typeDefs,
});
/**
* Types
*/
export type PostOrderByInput = 'id_ASC' |
'id_DESC' |
'isPublished_ASC' |
'isPublished_DESC' |
'title_ASC' |
'title_DESC' |
'text_ASC' |
'text_DESC' |
'updatedAt_ASC' |
'updatedAt_DESC' |
'createdAt_ASC' |
'createdAt_DESC'
export type PostOrderByInput =
| 'id_ASC'
| 'id_DESC'
| 'isPublished_ASC'
| 'isPublished_DESC'
| 'title_ASC'
| 'title_DESC'
| 'text_ASC'
| 'text_DESC'
| 'updatedAt_ASC'
| 'updatedAt_DESC'
| 'createdAt_ASC'
| 'createdAt_DESC';
export type MutationType = 'CREATED' |
'UPDATED' |
'DELETED'
export type MutationType = 'CREATED' | 'UPDATED' | 'DELETED';
export interface PostWhereUniqueInput {
id?: ID_Input
id?: ID_Input;
}
export interface PostCreateInput {
isPublished?: Boolean
title: String
text: String
isPublished?: Boolean;
title: String;
text: String;
}
export interface PostUpdateInput {
isPublished?: Boolean
title?: String
text?: String
isPublished?: Boolean;
title?: String;
text?: String;
}
export interface PostSubscriptionWhereInput {
AND?: PostSubscriptionWhereInput[] | PostSubscriptionWhereInput
OR?: PostSubscriptionWhereInput[] | PostSubscriptionWhereInput
NOT?: PostSubscriptionWhereInput[] | PostSubscriptionWhereInput
mutation_in?: MutationType[] | MutationType
updatedFields_contains?: String
updatedFields_contains_every?: String[] | String
updatedFields_contains_some?: String[] | String
node?: PostWhereInput
AND?: PostSubscriptionWhereInput[] | PostSubscriptionWhereInput;
OR?: PostSubscriptionWhereInput[] | PostSubscriptionWhereInput;
NOT?: PostSubscriptionWhereInput[] | PostSubscriptionWhereInput;
mutation_in?: MutationType[] | MutationType;
updatedFields_contains?: String;
updatedFields_contains_every?: String[] | String;
updatedFields_contains_some?: String[] | String;
node?: PostWhereInput;
}
export interface PostWhereInput {
AND?: PostWhereInput[] | PostWhereInput
OR?: PostWhereInput[] | PostWhereInput
NOT?: PostWhereInput[] | PostWhereInput
id?: ID_Input
id_not?: ID_Input
id_in?: ID_Input[] | ID_Input
id_not_in?: ID_Input[] | ID_Input
id_lt?: ID_Input
id_lte?: ID_Input
id_gt?: ID_Input
id_gte?: ID_Input
id_contains?: ID_Input
id_not_contains?: ID_Input
id_starts_with?: ID_Input
id_not_starts_with?: ID_Input
id_ends_with?: ID_Input
id_not_ends_with?: ID_Input
isPublished?: Boolean
isPublished_not?: Boolean
title?: String
title_not?: String
title_in?: String[] | String
title_not_in?: String[] | String
title_lt?: String
title_lte?: String
title_gt?: String
title_gte?: String
title_contains?: String
title_not_contains?: String
title_starts_with?: String
title_not_starts_with?: String
title_ends_with?: String
title_not_ends_with?: String
text?: String
text_not?: String
text_in?: String[] | String
text_not_in?: String[] | String
text_lt?: String
text_lte?: String
text_gt?: String
text_gte?: String
text_contains?: String
text_not_contains?: String
text_starts_with?: String
text_not_starts_with?: String
text_ends_with?: String
text_not_ends_with?: String
AND?: PostWhereInput[] | PostWhereInput;
OR?: PostWhereInput[] | PostWhereInput;
NOT?: PostWhereInput[] | PostWhereInput;
id?: ID_Input;
id_not?: ID_Input;
id_in?: ID_Input[] | ID_Input;
id_not_in?: ID_Input[] | ID_Input;
id_lt?: ID_Input;
id_lte?: ID_Input;
id_gt?: ID_Input;
id_gte?: ID_Input;
id_contains?: ID_Input;
id_not_contains?: ID_Input;
id_starts_with?: ID_Input;
id_not_starts_with?: ID_Input;
id_ends_with?: ID_Input;
id_not_ends_with?: ID_Input;
isPublished?: Boolean;
isPublished_not?: Boolean;
title?: String;
title_not?: String;
title_in?: String[] | String;
title_not_in?: String[] | String;
title_lt?: String;
title_lte?: String;
title_gt?: String;
title_gte?: String;
title_contains?: String;
title_not_contains?: String;
title_starts_with?: String;
title_not_starts_with?: String;
title_ends_with?: String;
title_not_ends_with?: String;
text?: String;
text_not?: String;
text_in?: String[] | String;
text_not_in?: String[] | String;
text_lt?: String;
text_lte?: String;
text_gt?: String;
text_gte?: String;
text_contains?: String;
text_not_contains?: String;
text_starts_with?: String;
text_not_starts_with?: String;
text_ends_with?: String;
text_not_ends_with?: String;
}
/*
@@ -460,7 +539,7 @@ export interface PostWhereInput {
*/
export interface Node {
id: ID_Output
id: ID_Output;
}
/*
@@ -468,21 +547,21 @@ export interface Node {
*/
export interface PageInfo {
hasNextPage: Boolean
hasPreviousPage: Boolean
startCursor?: String
endCursor?: String
hasNextPage: Boolean;
hasPreviousPage: Boolean;
startCursor?: String;
endCursor?: String;
}
export interface BatchPayload {
count: Long
count: Long;
}
export interface PostPreviousValues {
id: ID_Output
isPublished: Boolean
title: String
text: String
id: ID_Output;
isPublished: Boolean;
title: String;
text: String;
}
/*
@@ -490,27 +569,27 @@ export interface PostPreviousValues {
*/
export interface PostConnection {
pageInfo: PageInfo
edges: PostEdge[]
aggregate: AggregatePost
pageInfo: PageInfo;
edges: PostEdge[];
aggregate: AggregatePost;
}
export interface PostSubscriptionPayload {
mutation: MutationType
node?: Post
updatedFields?: String[]
previousValues?: PostPreviousValues
mutation: MutationType;
node?: Post;
updatedFields?: String[];
previousValues?: PostPreviousValues;
}
export interface Post extends Node {
id: ID_Output
isPublished: Boolean
title: String
text: String
id: ID_Output;
isPublished: Boolean;
title: String;
text: String;
}
export interface AggregatePost {
count: Int
count: Int;
}
/*
@@ -518,33 +597,33 @@ export interface AggregatePost {
*/
export interface PostEdge {
node: Post
cursor: String
node: Post;
cursor: String;
}
/*
The `Boolean` scalar type represents `true` or `false`.
*/
export type Boolean = boolean
export type Boolean = boolean;
/*
The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
*/
export type String = string
export type String = string;
/*
The `Long` scalar type represents non-fractional signed whole numeric values.
Long can represent values between -(2^63) and 2^63 - 1.
*/
export type Long = string
export type Long = string;
/*
The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID.
*/
export type ID_Input = string | number
export type ID_Output = string
export type ID_Input = string | number;
export type ID_Output = string;
/*
The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.
*/
export type Int = number
export type Int = number;

View File

@@ -6,11 +6,11 @@ import * as log from 'fancy-log';
// Has to be a hardcoded object due to build order
const packages = {
'common': createProject('packages/common/tsconfig.json'),
'core': createProject('packages/core/tsconfig.json'),
'microservices': createProject('packages/microservices/tsconfig.json'),
'websockets': createProject('packages/websockets/tsconfig.json'),
'testing': createProject('packages/testing/tsconfig.json'),
common: createProject('packages/common/tsconfig.json'),
core: createProject('packages/core/tsconfig.json'),
microservices: createProject('packages/microservices/tsconfig.json'),
websockets: createProject('packages/websockets/tsconfig.json'),
testing: createProject('packages/testing/tsconfig.json'),
'platform-express': createProject('packages/platform-express/tsconfig.json'),
'platform-fastify': createProject('packages/platform-fastify/tsconfig.json'),
'platform-socket.io': createProject(