Eliya Cohen
Eliya Cohen

Reputation: 11458

Firebase - Handle cloud events within NestJS Framework

I'm using NestJS as my backend Framework and Firebase.

To integrate Nest with Firebase on HTTP requests is simple as attaching the express instance of nest to Firebase:

const server: Express = express();

const bootstrap = async (expressInstance: Express) => {
  const app = await NestFactory.create(AppModule, expressInstance);
  await app.listen(3000);
  await app.init();
};

bootstrap(server);

exports.api = functions.https.onRequest(server);

But what about the other Google Functions (such as pubsub, firestore, auth, etc.)?

I'm building a subscription application, and I depend on functions.pubsub to check at the end of every day which subscriptions should I charge. It requires writing business logic that I want to write withing NestJs.

I'm trying to achieve something like this (in a nutshell):

functions.pubsub
    .topic('topic')
    .onPublish(app.getService(Service).method);

Upvotes: 8

Views: 2838

Answers (2)

Slava Dobromyslov
Slava Dobromyslov

Reputation: 3269

Found a new solution for standalone applications: https://docs.nestjs.com/standalone-applications

You don't need to bootstrap NestJS with Express server to handle PubSub messages.

export const subscriptions = functions
  .pubsub
  .topic('cron-topic')
  .onPublish((context, message) => {
    const app = await NestFactory.create(ApplicationModule);
    return app.get(SubscribeService).initDailyCharges(context, message);
  });

Upvotes: 3

Eliya Cohen
Eliya Cohen

Reputation: 11458

Turns out I was very close to the solution. instead of getService, I had to use get, like so:

const bootstrap = async (expressInstance: Express) => {
  const app = await NestFactory.create(AppModule, expressInstance);
  await app.init();

  return app;
};

const main = bootstrap(server);

export const subscriptions = functions
  .pubsub
  .topic('cron-topic')
  .onPublish((context, message) => main.then(app => {
    return app.get(SubscribeService).initDailyCharges(context, message));
  });

Upvotes: 7

Related Questions