Skip to content

Commit

Permalink
add example for nestjs and fastify
Browse files Browse the repository at this point in the history
  • Loading branch information
zgid123 committed Apr 15, 2023
1 parent 1ad75ae commit d922265
Show file tree
Hide file tree
Showing 21 changed files with 3,104 additions and 43 deletions.
1 change: 1 addition & 0 deletions examples/fastify/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Example for Fastify
23 changes: 23 additions & 0 deletions examples/fastify/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "@examples/fastify",
"version": "1.0.0",
"description": "Example for Fastify",
"type": "module",
"scripts": {
"dev": "vite-node -w src/main.ts",
"build": "vite build"
},
"dependencies": {
"@kafka-ts/fastify-consumer": "workspace:*",
"@kafka-ts/fastify-producer": "workspace:*",
"detect-port": "^1.5.1",
"fastify": "^4.15.0",
"vite": "^4.2.1"
},
"devDependencies": {
"@fastify/vite": "^4.0.0",
"@types/detect-port": "^1.3.2",
"fastify-cli": "^5.7.1",
"vite-node": "^0.30.0"
}
}
5 changes: 5 additions & 0 deletions examples/fastify/src/config/fastify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import Fastify from 'fastify';

export const fastify = Fastify({
logger: process.env.NODE_ENV === 'production' ? false : true,
});
3 changes: 3 additions & 0 deletions examples/fastify/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const EXCHANGE = 'topic';
export const QUEUE = 'queue';
export const ROUTE = 'route';
92 changes: 92 additions & 0 deletions examples/fastify/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import detect from 'detect-port';
import KafkaProducer from '@kafka-ts/fastify-producer';
import KafkaConsumer from '@kafka-ts/fastify-consumer';

import { fastify } from 'config/fastify';

async function bootstrap(): Promise<typeof fastify> {
fastify.register(KafkaProducer, {
brokers: ['localhost:9092'],
});

fastify.register(KafkaConsumer, [
{
brokers: ['localhost:9092'],
consumerOptions: {
groupId: 'test-id',
},
},
{
clientId: 'test-client',
brokers: ['localhost:9092'],
consumerOptions: {
groupId: 'test-id-2',
},
},
]);

fastify.get('/', async (_request, reply) => {
const result = await fastify.kafkaProducer.publish({
topicMessages: {
topic: 'topic',
messages: [
{
value: 'hello from producer',
},
],
},
});

console.log(result);

reply.send('Ok');
});

fastify.get('/message', async (_request, reply) => {
const result = await fastify.kafkaProducer.publish({
topicMessages: {
topic: 'topic_2',
messages: [
{
value: 'hello from producer',
},
],
},
});

console.log(result);

reply.send('Ok');
});

const port = await detect(3_000);
await fastify.listen({
port,
});

fastify.kafkaConsumer.subscribe(
{
topics: ['topic'],
},
async (data, context) => {
console.log('data', data);
console.log('context.batch', context.batch);
},
);

fastify.kafkaConsumer.subscribe(
{
clientId: 'test-client',
type: 'message',
topics: ['topic_2'],
},
async (data, context) => {
console.log('data', data);
console.log('context.message', context.message);
},
);

return fastify;
}

bootstrap();
25 changes: 25 additions & 0 deletions examples/fastify/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"baseUrl": "src",
"declaration": true,
"emitDecoratorMetadata": true,
"incremental": true,
"module": "esnext",
"noEmit": false,
"noFallthroughCasesInSwitch": false,
"noImplicitAny": false,
"outDir": "dist",
"sourceMap": true,
"strictBindCallApply": false,
"strictNullChecks": false
},
"include": [
"src"
],
"exclude": [
"dist",
"node_modules"
]
}
45 changes: 45 additions & 0 deletions examples/fastify/vite.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { resolve } from 'path';
import { readdirSync } from 'fs';
import detect from 'detect-port';
import { defineConfig, type UserConfigExport } from 'vite';

export default async function config(): Promise<UserConfigExport> {
const port = await detect(3_000);

const items = readdirSync(resolve(__dirname, 'src'));

return defineConfig({
server: {
port,
watch: {
usePolling: true,
},
},
resolve: {
alias: items.map((item) => {
if (/\.(t|j)sx?$/.test(item)) {
const name = item.replace(/\.(t|j)sx?$/, '');

return {
find: name,
replacement: `/src/${name}`,
};
} else {
return {
find: item,
replacement: `/src/${item}`,
};
}
}),
},
build: {
ssr: true,
ssrEmitAssets: true,
rollupOptions: {
input: {
main: './src/main.ts',
},
},
},
});
}
19 changes: 19 additions & 0 deletions examples/nestjs/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint/eslint-plugin"
],
"extends": [
"../../.eslintrc.json",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"root": true,
"env": {
"node": true
},
"ignorePatterns": [
".eslintrc.json"
],
"rules": {}
}
1 change: 1 addition & 0 deletions examples/nestjs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Example for NestJS
8 changes: 8 additions & 0 deletions examples/nestjs/nest-cli.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}
35 changes: 35 additions & 0 deletions examples/nestjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "@examples/nestjs",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"dev": "nest start --watch",
"start:prod": "node dist/main"
},
"dependencies": {
"@kafka-ts/nestjs-consumer": "workspace:*",
"@kafka-ts/nestjs-producer": "workspace:*",
"@nestjs/common": "^9.4.0",
"@nestjs/core": "^9.4.0",
"@nestjs/microservices": "^9.4.0",
"@nestjs/platform-express": "^9.4.0",
"detect-port": "^1.5.1",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.0"
},
"devDependencies": {
"@nestjs/cli": "^9.3.0",
"@nestjs/schematics": "^9.1.0",
"@types/detect-port": "^1.3.2",
"@types/express": "^4.17.17",
"@types/node": "18.15.11",
"source-map-support": "^0.5.21",
"ts-loader": "^9.4.2",
"ts-node": "^10.9.1",
"tsconfig-paths": "4.2.0"
}
}
9 changes: 9 additions & 0 deletions examples/nestjs/src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Controller, Get } from '@nestjs/common';

@Controller()
export class AppController {
@Get('/health')
public health(): string {
return 'Ok!';
}
}
11 changes: 11 additions & 0 deletions examples/nestjs/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';

import { AppController } from './app.controller';
import { ConsumerModule } from './consumer/consumer.module';
import { ProducerModule } from './producer/producer.module';

@Module({
imports: [ConsumerModule, ProducerModule],
controllers: [AppController],
})
export class AppModule {}
39 changes: 39 additions & 0 deletions examples/nestjs/src/consumer/consumer.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Controller } from '@nestjs/common';
import {
Ctx,
Payload,
Subscribe,
SubscribeMessage,
KafkaMessageContext,
KafkaBatchMessageContext,
} from '@kafka-ts/nestjs-consumer';

@Controller()
export class ConsumerController {
@Subscribe({
topics: ['topic'],
})
public async handleSubscribe(
@Payload() data: string[],
@Ctx() context: KafkaBatchMessageContext,
): Promise<string> {
console.log('data', data);
console.log('context.batch', context.batch);

return 'Ok!';
}

@SubscribeMessage({
clientId: 'test-client',
topics: ['topic_2'],
})
public async handleSubscribeMessage(
@Payload() data: string,
@Ctx() context: KafkaMessageContext,
): Promise<string> {
console.log('data', data);
console.log('context.message', context.message);

return 'Ok!';
}
}
8 changes: 8 additions & 0 deletions examples/nestjs/src/consumer/consumer.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';

import { ConsumerController } from './consumer.controller';

@Module({
controllers: [ConsumerController],
})
export class ConsumerModule {}
35 changes: 35 additions & 0 deletions examples/nestjs/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import detect from 'detect-port';
import { NestFactory } from '@nestjs/core';
import { KafkaConsumer } from '@kafka-ts/nestjs-consumer';

import { AppModule } from './app.module';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

app.connectMicroservice(
KafkaConsumer.createService([
{
brokers: ['localhost:9092'],
consumerOptions: {
groupId: 'test-id',
},
},
{
clientId: 'test-client',
brokers: ['localhost:9092'],
consumerOptions: {
groupId: 'test-id-2',
},
},
]),
);

const port = await detect(3_000);
await app.startAllMicroservices();
await app.listen(port);

console.log(`Run on ${port}`);
}

bootstrap();
Loading

0 comments on commit d922265

Please sign in to comment.