Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 663
Eliya Cohen Avatar asked Nov 14 '18 19:11

Eliya Cohen


2 Answers

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));
  });
like image 135
Eliya Cohen Avatar answered Nov 16 '22 08:11

Eliya Cohen


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);
  });
like image 1
Viacheslav Dobromyslov Avatar answered Nov 16 '22 08:11

Viacheslav Dobromyslov