Giter Site home page Giter Site logo

nestjs-amqp's Introduction

Awesome Nest Nest Powered

Nestjs Amqp

An AMQP connection service for NestJS.

Using the AMQPlib for node package.

This package was intented to be used in execution content and provides a basic AMQPlib connection via the providers to allow developers to develop their amqp queue consumers and publishers. For microservice transport; check out the docs for rabbitMQ.

Install

$ yarn add nestjs-amqp
$ yarn add -D @types/amqplib

Basic usage

import {Module} from '@nestjs/common';
import {AmqpModule} from 'nestjs-amqp';

@Module({
  imports: [AmqpModule.forRoot({
    name: 'rabbitmq',
    hostname: 'localhost',
    port: 5672,
    username: 'test',
    password: 'test',
  })],
})
export default class AppModule {}

Advanced usage

Usage with nestjs-config

import {Module} from '@nestjs/common';
import {AmqpModule} from 'nestjs-amqp';
import {ConfigModule, ConfigService} from 'nestjs-config';
import * as path from 'path';

@Module({
  imports: [
    ConfigModule.load(path.resolve(__dirname, 'config', '**/*.ts')),
    AmqpModule.forRootAsync({
      useFactory: (config: ConfigService) => config.get('amqp'),
      inject: [ConfigService],
    }),
  ],
})
export default class AppModule {}

//src/config/amqp.ts
export default {
  name: 'rabbitmq',
  hostname: process.env.AMQP_HOST,
  port: process.env.AMQP_PORT,
  username: process.env.USERNAME,
  password: process.env.PASSWORD,
} 

Unfortunately multiple connections are unavailable when using the forRootAsync method.

Usage in custom provider

It is possible to inject the AmqpConnection in a factory of a custom provider if one needs such capability.

import { Connection as AmqpConnection } from 'amqplib';
import {ConfigService} from 'nestjs-config';
import {createConnectionToken} from 'nestjs-amqp/utils';

export const queueServiceProvider = {
    provider: 'QueueService',
    useFactory: (amqp: AmqpConnection, configService: ConfigService) => new QueueService(amqp, config.get('queue')),
    inject: [createConnectionToken('default'), ConfigService],
}

It's also possible to give your connections names, if you have done so then use the name of your connection instead of default.

Connection Decorators

import {Module} from '@nestjs/common';
import {AmqpModule} from 'nestjs-amqp';

@Module({
  imports: [AmqpModule.forRoot([
    {
      hostname: 'test:test@localhost',
    }, 
    {
      username: 'test',
      password: 'test',
      hostname: 'localhost',
      port: 5672,
      protocol: 'amqps',
      name: 'test',
    }
  ])],
})
export default class ExecutionModule {
}
import {Injectable} from '@nestjs/common';
import {InjectAmqpConnection} from 'nestjs-amqp';
import {Connection} from 'amqplib';

@Injectable()
export default class TestService {
  constructor(
    @InjectAmqpConnection('test')
    private readonly connectionTest: Connection, //gets connection with name 'test' defined in module
    @InjectAmqpConnection(0)
    private readonly connection0: Connection, //gets first defined connection without a name
  ) {}
}

Use InjectAmqpConnection without a parameter for default connection

Example publish

import {Injectable, Logger} from '@nestjs/common';
import {InjectAmqpConnection} from 'nestjs-amqp';
import {Connection} from 'amqplib';

@Injectable()
export default class TestProvider {
  constructor(
    @InjectAmqpConnection()
    private readonly amqp: Connection,
  ) {}
  async publish(message: string)  {
    await this.amqp.createChannel((err, channel) => {
      if (err != null) {
        Logger.alert(err, 'TestProvider');
      }
      channel.assertQueue('test_queue_name');
      channel.sendToQueue('test_queue_name', message);
    });
  }
}

More information and examples about amqplib can be found here.

Available Options

Name For Default
hostname The host url for the connection localhost
port The port of the amqp host 5672
name The name of the connection default or the array key index [0]
retrys The amount of retry attempts before surrender 3
retryDelay The amount of milliseconds to wait before attempting retry 3000
protocol The protocol for the connection amqp
username The username for the connection
password The password for the connection
locale The desired locale for error messages en_US
frameMax The size in bytes of the maximum frame allowed over the connection 0
heartbeat The period of the connection heartbeat in seconds 0
vhost What VHost shall be used /

Testing this package

In order to test first you need to start the rabbitmq container. We've provided a docker-compose file to make this easier.

$ docker-compose up -d 
$ yarn test

Navigate to localhost:15672 for rabbitmq manager, username and password are both guest

If you're using docker-machine or a VM then change the env for HOST in the .env file or create one using the provided .env.dist file.

Future implementation

WARNING: The below examples have not been implemented

So far this package manages multiple AMQP connections using the nestjs container and injects them into other providers.
Alternatively I'd like to implement something like this:

import {Injectable} from '@nestjs/common';
import {
  AmqpConnection,
  Consume,
  Publish,
  Message,
} from 'nestjs-amqp';

@Injectable()
@AmqpConnection()
export default class MyAmqpService {
   
  @Consume("queue_name", {
    noAck: true,
  })
  async listen(@Message message) {
    console.log('Message received', message);
    
    //send a message back
    this.publish();
  }

  @Publish("queue_name")
  async publish() {
    return "Send this to 'queue queue_name'";
  }
}

Then using executable context

import { NestFactory } from '@nestjs/core';
import QueueModule, { MyAmqpService } from './queue';

async function bootstrap() {
  const app = await NestFactory.create(QueueModule);
  const event = app.get(MyAmqpService);

  await event.listen();

}
bootstrap();

process.stdin.resume();

Or something similar to the above is what I'd like to implement

nestjs-amqp's People

Contributors

bashleigh avatar brunnerlivio avatar dependabot-preview[bot] avatar dependabot[bot] avatar edgar-p-yan avatar fenos avatar s33g avatar traoreak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

nestjs-amqp's Issues

Unable to resolve dependency tree with nestjs v7

When running npm install nestjs-amqp I got

โฏ npm install nestjs-amqp
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: @nestjs/[email protected]
npm ERR! node_modules/@nestjs/common
npm ERR!   @nestjs/common@"^7.6.15" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @nestjs/common@"^5.1.0 || ^6.0.3" from [email protected]
npm ERR! node_modules/nestjs-amqp
npm ERR!   nestjs-amqp@"*" from the root project

Right now I'm willing to try the --force option but it should be nice to update the peerDependencies or to know if/when this package will support nestjs 7

Improve readme

Add better documentation to the readme on how to use the package

Inject connection to factory

Is it possible to inject the AmqpConnection in a factory of a custom provider?

I tried this but without success:

import { Connection as AmqpConnection } from 'amqplib'
import { ConfigService } from 'nestjs-config'

export const queueServiceProvider = {
  provide: 'QueueService',
  useFactory: (amqp: AmqpConnection, configService: ConfigService) => {
    return new QueueService(amqp, configService.get('queue'))
  },
  inject: [AmqpConnection, ConfigService]
}

Inject connection to factory

Hello @bashleigh, I have trouble injecting a connection to a factory. I would be willing to submit a documentation PR for this as mentioned in #21 , but more importantly for me the createConnectionToken needs to be exported by default from the package. At the moment it's only accessible via import { createConnectionToken } from 'nestjs-amqp/dist/utils/create.tokens'; and not via nestjs/utils. Can I submit a PR that does that also or are you against exposing this function in that way ?

AmqpOptionsInterface error

Hi, when testing the library with the following code using "nestjs-amqp": "^0.1.9",

import {Module} from '@nestjs/common'
import {AmqpModule} from 'nestjs-amqp'
 
@Module({
  imports: [AmqpModule.forRoot({
    name: 'rabbitmq',
    hostname: 'localhost',
    port: 5672,
    username: 'test',
    password: 'test',
  })],
})
export default class AppModule {}

I'm seeing this error in VS Code. Any ideas?

Argument of type '{ name: string; hostname: string; port: number; username: string; password: string; }' is not assignable to parameter of type 'AmqpOptionsInterface | AmqpOptionsInterface[]'.
  Object literal may only specify known properties, and 'hostname' does not exist in type 'AmqpOptionsInterface | AmqpOptionsInterface[]'.ts(2345)

Create a class for the connection

Create a class to hold the connection and channel within.
Add methods to this to create queues, channels, topics etc and methods to subscribe and publish to queues.

Dependancy clean up

It would be a better idea to include @nestjs/common as a peer dependancy instead of a dependancy

Can not create channel with Channel Model

As I researched, the node amqp lib export two types of API, they are amqplib/channel_api and amqplib/callback_api.
By importing and using the amqplib/callback_api, I can create the connection, channel normally but amqplib/channel_api not.
So my question is how can I set up to use the Channel Model instead of the Callback model?

Furthermore, Can anyone explain to me the difference between these types of models, since I can not see it in the official document?

Rascal

https://guidesmiths.github.io/rascal/

Have you looked at the rascal amqplib wrapper? It's wraps the queue with an EventEmitter, along with having a powerful config format for setting up queues and bindings.

I found it really easy to use. Much more easy than amqplib directly.

Error in module config of module

Following the steps in the readme result in type errors

AmqpModule.forRoot({
      name: 'rabbitmq',
      hostname: 'localhost',
      port: 5672,
      username: 'guest',
      password: 'guest',
    })

ERROR in app.module.ts(41,7):
TS2345: Argument of type '{ name: string; hostname: string; port: number; username: string; password: string; }' is not assignable to parameter of type 'AmqpOptionsInterface | AmqpOptionsInterface[]'.
Object literal may only specify known properties, and 'hostname' does not exist in type 'AmqpOptionsInterface | AmqpOptionsInterface[]'.

Seems that it can't resolve the inherited Options from amqplib, somethink I'm missing here?

Can not resolve dependencies

I tried to send a message, like described here, but I'm getting the following error:

[ExceptionHandler] Nest can't resolve dependencies of the AppAmqp (?). Please make sure that the argument at index [0] is available in the AppModule context. +25ms

This is my provider:

import {Injectable, Logger} from '@nestjs/common';
import {InjectAmqpConnection} from 'nestjs-amqp';

@Injectable()
export class AppAmqp {
    constructor(@InjectAmqpConnection() private readonly amqp: any) {}
    async publish(message: string)  {
        await this.amqp.createChannel((err, channel) => {
            if (err != null) {
                Logger.warn(err, 'TestProvider');
            }
            channel.assertQueue('test_queue_name');
            channel.sendToQueue('test_queue_name', message);
        });
    }
}

And here is the AppModule

import { Module } from '@nestjs/common';
import { AmqpModule } from 'nestjs-amqp';
import { AppController } from './app.controller';
import { AppAmqp } from './app.amqp';

@Module({
    imports: [AmqpModule.forRoot({
        hostname: 'localhost',
        port: 5672,
    })],
    controllers: [AppController],
    providers: [AppAmqp],
})
export class AppModule {}

Controller:

@Controller()
export class AppController {
  constructor(
      private readonly appAmqp: AppAmqp,
  ) {}

  @Get('/:name')
  async root(@Param('name') name): Promise<string> {
    await this.appAmqp.publish(name);
  }
}

What am I missing?

Testing

Add the ability to test the package using docker, travis, jest and coveralls to show the overall coverage of tests

Decorators

If possible create a series of decorators to achieve the following implementation

@AmqpConnection('default')
export default class MyAmqpProvider {

    @Consume('queue_name', { ack: false})
    async listen(message) {
        console.log('message', message.content.toString());
    }
    
    @Exchange('exchange_name', 'queue_name')
    async exchange() {
        return 'send me to the queue';
    }
}

Error: Nest can't resolve dependencies of the AlertProvider (?).

I'm new to nest.js. I don't know why Nest cant resolve dependencies. And there is nothing in README. I had found something similar in closed issues but it didn't help. Here is an error

Error: Nest can't resolve dependencies of the AlertProvider (?). Please make sure that the argument at index [0] is available in the AlertModule context.

Here is my files (cleaned up a little bit):

// app/app.module.ts
import { Module } from '@nestjs/common';

@Module({
  imports: [
    ConfigModule.load(
      path.resolve(process.cwd(), 'config', '**/!(*.d).{ts,js}'),
    ),
    AmqpModule.forRootAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => config.get('amqp'),
    }),
    //...
})
export class AppModule implements NestModule
// config/amqp.ts
export default {
  name: 'default',
  hostname: process.env.AMQP_HOST || 'mq-service',
  port: process.env.AMQP_PORT || 5672,
  username: process.env.USERNAME || 'guest',
  password: process.env.PASSWORD || 'guest',
};
// alert/alert.module.ts
import { Module } from '@nestjs/common';
import { AmqpModule } from 'nestjs-amqp';
import { AlertService } from './alert.service';
import { AlertProvider } from './alert.provider';

@Module({
  imports: [
    AmqpModule.forFeature(),  // The error also occurs without this line
  ],
  providers: [
    AlertService,
    AlertProvider,
  ],
})
export class AlertModule {}
// alert/alert.provider.ts
import { InjectAmqpConnection } from 'nestjs-amqp';

const QUEUE = 'alerts';

export class AlertProvider {
  constructor(
    @InjectAmqpConnection('default') private readonly amqp,
  ) {
    this.setupListeners();
  }

  async setupListeners() {
    const channel = await this.amqp.createChannel();
    await channel.assertQueue(QUEUE);
    channel.consume(QUEUE, (msg) => {
      if (msg === null) {
        return;
      }
      console.log(msg.content.toString());
    });
  }
}

Maybe you can suggest me something.
I use nest@v6 and latest version of nestjs-amqp

Unable to connect via regular string

Hi, I have a remote message broker, RabbitMQ, that I connect to via a string URL. Is it possible to pass only a string without passing an object from the parameters?

Manual reconnect

Is it possible to reconnect to rabbitmq when it was been restarted or something else?

Jest E2E would not exit

I am writing an E2E test for my app which imports nestjs-amqp. The test would not exit after all the test cases finished. I guess it is the AMQP connection was not closed. If it is, should I close it manually or should nestjs-amqp close it automatically through something like OnModuleDestroy?

nestjs/nest#899

Hangs on channel creation

Module setup connects fine with no errors:

import { AmqpModule } from "nestjs-amqp";
import RabbitService from "./rabbit.service";
import { ConfigModule, ConfigService } from "nestjs-config";
import { Module } from "@nestjs/common";
@Module({
    imports: [
      ConfigModule,
      AmqpModule.forRootAsync({
        useFactory: async (configService: ConfigService) => {
          return configService.get("rabbit");
        },
        inject: [ConfigService]
      }),
    ],
    providers: [
      RabbitService,
    ],
    exports: [RabbitService]
  })
export class RabbitModule {}

Service does not console log anything inside of 'createChannel'.

import {Injectable, Logger} from "@nestjs/common";
import {InjectAmqpConnection} from "nestjs-amqp";

@Injectable()
export default class RabbitService {
    constructor(@InjectAmqpConnection() private readonly amqp) {}

    private readonly logger = new Logger(RabbitService.name);

    async publish(message: string)  {
      await this.amqp.createChannel((err, channel) => {
          if (err != null) {
          this.logger.log(err, "Error connecting");
          }
          console.log("Adding");
          channel.assertQueue("location_validate");
          channel.sendToQueue("location_validate", "Hello test");
        });
    }
}

Logged out the connection:

Connection {
  _events: [Object: null prototype] {
    frameError: [Function: bound ],
    error: [Function: bound ],
    close: [Function: bound ],
    blocked: [Function: bound ],
    unblocked: [Function: bound ]
  },
  _eventsCount: 5,
  _maxListeners: undefined,
  stream: Socket {
    connecting: false,
    _hadError: false,
    _parent: null,
    _host: null,
    _readableState: ReadableState {
      objectMode: false,
      highWaterMark: 16384,
      buffer: BufferList { head: null, tail: null, length: 0 },
      length: 0,
      pipes: null,
      pipesCount: 0,
      flowing: false,
      ended: false,
      endEmitted: false,
      reading: true,
      sync: false,
      needReadable: true,
      emittedReadable: false,
      readableListening: true,
      resumeScheduled: false,
      paused: true,
      emitClose: false,
      autoDestroy: false,
      destroyed: false,
      defaultEncoding: 'utf8',
      awaitDrain: 0,
      readingMore: false,
      decoder: null,
      encoding: null
    },
    readable: true,
    _events: [Object: null prototype] {
      end: [Array],
      error: [Array],
      drain: [Function],
      readable: [Function: go]
    },
    _eventsCount: 4,
    _maxListeners: undefined,
    _writableState: WritableState {
      objectMode: false,
      highWaterMark: 16384,
      finalCalled: false,
      needDrain: false,
      ending: false,
      ended: false,
      finished: false,
      destroyed: false,
      decodeStrings: false,
      defaultEncoding: 'utf8',
      length: 0,
      writing: false,
      corked: 0,
      sync: false,
      bufferProcessing: false,
      onwrite: [Function: bound onwrite],
      writecb: null,
      writelen: 0,
      bufferedRequest: null,
      lastBufferedRequest: null,
      pendingcb: 0,
      prefinished: false,
      errorEmitted: false,
      emitClose: false,
      autoDestroy: false,
      bufferedRequestCount: 0,
      corkedRequestsFree: [Object]
    },
    writable: true,
    allowHalfOpen: false,
    _sockname: null,
    _pendingData: null,
    _pendingEncoding: '',
    server: null,
    _server: null,
    [Symbol(asyncId)]: 12,
    [Symbol(kHandle)]: TCP {
      reading: true,
      onconnection: null,
      [Symbol(owner)]: [Circular]
    },
    [Symbol(lastWriteQueueSize)]: 0,
    [Symbol(timeout)]: null,
    [Symbol(kBytesRead)]: 0,
    [Symbol(kBytesWritten)]: 0
  },
  muxer: Mux {
    newStreams: [],
    oldStreams: [],
    blocked: false,
    scheduledRead: false,
    out: Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: null,
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: null,
      _server: null,
      [Symbol(asyncId)]: 12,
      [Symbol(kHandle)]: [TCP],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0
    }
  },
  rest: <Buffer >,
  frameMax: 4096,
  sentSinceLastCheck: true,
  recvSinceLastCheck: true,
  expectSocketClose: false,
  freeChannels: BitSet { words: [], wordsInUse: 0 },
  channels: [ { channel: [Object], buffer: [Socket] } ],
  serverProperties: {
    capabilities: {
      publisher_confirms: true,
      exchange_exchange_bindings: true,
      'basic.nack': true,
      consumer_cancel_notify: true,
      'connection.blocked': true,
      consumer_priorities: true,
      authentication_failure_close: true,
      per_consumer_qos: true,
      direct_reply_to: true
    },
    cluster_name: '[email protected]',
    copyright: 'Copyright (C) 2007-2019 Pivotal Software, Inc.',
    information: 'Licensed under the MPL.  See https://www.rabbitmq.com/',
    platform: 'Erlang/OTP 22.0.2',
    product: 'RabbitMQ',
    version: '3.7.15'
  },
  channelMax: 2047,
  heartbeat: 60,
  heartbeater: Heart {
    _events: [Object: null prototype] { timeout: [Function], beat: [Function] },
    _eventsCount: 2,
    _maxListeners: undefined,
    interval: 60,
    sendTimer: Timeout {
      _idleTimeout: 30000,
      _idlePrev: [TimersList],
      _idleNext: [TimersList],
      _idleStart: 3073,
      _onTimeout: [Function: bound ],
      _timerArgs: undefined,
      _repeat: 30000,
      _destroyed: false,
      [Symbol(refed)]: true,
      [Symbol(asyncId)]: 880,
      [Symbol(triggerId)]: 877
    },
    recvTimer: Timeout {
      _idleTimeout: 60000,
      _idlePrev: [TimersList],
      _idleNext: [TimersList],
      _idleStart: 3073,
      _onTimeout: [Function: bound ],
      _timerArgs: undefined,
      _repeat: 60000,
      _destroyed: false,
      [Symbol(refed)]: true,
      [Symbol(asyncId)]: 881,
      [Symbol(triggerId)]: 877
    }
  },
  accept: [Function: mainAccept]
}

Logged out the channel:

Channel {
  _events: [Object: null prototype] {
    ack: [Function: bound ],
    nack: [Function: bound ],
    delivery: [Function: bound ],
    cancel: [Function: bound ]
  },
  _eventsCount: 4,
  _maxListeners: undefined,
  connection: Connection {
    _events: [Object: null prototype] {
      frameError: [Function: bound ],
      error: [Function: bound ],
      close: [Function: bound ],
      blocked: [Function: bound ],
      unblocked: [Function: bound ]
    },
    _eventsCount: 5,
    _maxListeners: undefined,
    stream: Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: null,
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: null,
      _server: null,
      [Symbol(asyncId)]: 12,
      [Symbol(kHandle)]: [TCP],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0
    },
    muxer: Mux {
      newStreams: [],
      oldStreams: [],
      blocked: false,
      scheduledRead: false,
      out: [Socket]
    },
    rest: <Buffer >,
    frameMax: 4096,
    sentSinceLastCheck: true,
    recvSinceLastCheck: true,
    expectSocketClose: false,
    freeChannels: BitSet { words: [Array], wordsInUse: 1 },
    channels: [ [Object], [Object] ],
    serverProperties: {
      capabilities: [Object],
      cluster_name: '[email protected]'
      copyright: 'Copyright (C) 2007-2019 Pivotal Software, Inc.',
      information: 'Licensed under the MPL.  See https://www.rabbitmq.com/',
      platform: 'Erlang/OTP 22.0.2',
      product: 'RabbitMQ',
      version: '3.7.15'
    },
    channelMax: 2047,
    heartbeat: 60,
    heartbeater: Heart {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      interval: 60,
      sendTimer: Timeout {
        _idleTimeout: 30000,
        _idlePrev: [TimersList],
        _idleNext: [TimersList],
        _idleStart: 2916,
        _onTimeout: [Function: bound ],
        _timerArgs: undefined,
        _repeat: 30000,
        _destroyed: false,
        [Symbol(refed)]: true,
        [Symbol(asyncId)]: 813,
        [Symbol(triggerId)]: 810
      },
      recvTimer: Timeout {
        _idleTimeout: 60000,
        _idlePrev: [TimersList],
        _idleNext: [TimersList],
        _idleStart: 2916,
        _onTimeout: [Function: bound ],
        _timerArgs: undefined,
        _repeat: 60000,
        _destroyed: false,
        [Symbol(refed)]: true,
        [Symbol(asyncId)]: 814,
        [Symbol(triggerId)]: 810
      }
    },
    accept: [Function: mainAccept]
  },
  reply: null,
  pending: [],
  lwm: 1,
  unconfirmed: [],
  handleMessage: [Function: acceptDeliveryOrReturn],
  consumers: {},
  ch: 1
}

Example doesn't work

Hello nestjs/amqp community,

I would like to integrate this library to my project, but I am having a problem to run example from documentation.

ERROR:

Nest can't resolve dependencies of the CrawlerService (?, AMQP_CONNECTION_PROVIDER_0). Please make sure that the argument AMQP_CONNECTION_PROVIDER_test at index [0] is available in the CrawlerModule context.

Potential solutions:
- If AMQP_CONNECTION_PROVIDER_test is a provider, is it part of the current CrawlerModule?
- If AMQP_CONNECTION_PROVIDER_test is exported from a separate @Module, is that module imported within CrawlerModule?
  @Module({
    imports: [ /* the Module containing AMQP_CONNECTION_PROVIDER_test */ ]
  })

My app.moule.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ENV_DB } from 'const/env';
import { BucketModule } from 'modules/core/bucket/bucket.module';
import { CrawlerModule } from 'modules/core/crawler/crawler.module';
import { ItemsModule } from 'modules/items/items.module';
import { ProvidersModule } from 'modules/providers/providers.module';
import { UsersModule } from 'modules/users/users.module';

import { AmqpModule } from 'nestjs-amqp';
@Module({
	imports: [
		AmqpModule.forRoot({
			username: 'xxxxx',
			password: 'xxxxxx',
			hostname: 'xxxxxx',
			port: 5672,
			protocol: 'amqp',
			name: 'test',
		}), 
	],
})
export class AppModule { }

My crawler.module.ts

@Module({
	imports: [
		AmqpModule.forFeature(), 
	],
	providers: [
		CrawlerService, 
	],
	exports: [CrawlerService],
})

export class CrawlerModule { }

My crawler.service.ts

@Injectable()
export class CrawlerService { 

	constructor(
		@InjectAmqpConnection()
		private readonly amqp: Connection,
	) { }

	async test(message: string) {
		await this.amqp.createChannel((err, channel) => {
			if (err != null) {
				Logger.alert(err, 'TestProvider');
			}
			channel.assertQueue('test_queue_name');
			channel.sendToQueue('test_queue_name', message);
		});
	}

	public async process() {
		await this.test('test') 
	}

}

What is wrong? Looks like I have all steps from example.

Thank you for any help.

Update nestjs/common peer dependency

The latest nestjs/common dependency is 9.1.6, could this package update to that accordingly instead of sticking to 5.1.0 || 6.0.3 version respectively?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.