Develop the New Service Placeholder

Learn how to develop the placeholder for the new service for your web application.

Firebase expects all functions we develop to be exported from the services/web/firebase/functions/src/index.ts module. Currently, we have the “helloWorld” named export, which creates a Cloud Function service called helloWorld. We will have to export all our new services from that file as well.

A few words about naming conventions:

Names must be meaningful and self-explanatory, so that anyone who reads the code understands what they mean. This means less cognitive load on anyone involved and far fewer questions along the lines of “What’s the name of that service that cross-posts a blog post to dev.to, again? Oh, and where can I find its source code?”

So, instead of calling our service goldfish.ts or even cross-post-service.ts, which do not tell us how they were triggered, we are going to create the following service:

services/web/firebase/functions/src/firestore/posts/oncreate/ cross-post-to-devto/index.ts

Without opening the file and reading a line of code, it is immediately clear to anyone when this service is called and what it does. Although our service only contains one file, we will create a directory so that larger services can be split into multiple files and still keep all files together in a service-specific directory. As we will see in a moment, this also allows us to place our test files right next to the service itself.

Developing the new service placeholder

How to create nested directories with a single command

There’s a few new directories. You could right-click to create a “New Folder”, type the name, click “OK” and repeat for each directory.

Or you can run the following two commands from the root of the project:

mkdir -p services/web/firebase/functions/src/firestore/posts/on-create/cross-post-to-devto

touch services/web/firebase/functions/src/firestore/posts/on-create/cross-post-to-devto/index.ts

The trick here is the -p flag for the mkdir command! As per mkdir --help, this flag means “no error if existing, make parent directories as needed”.

Click Run to open the terminal and create services/web/firebase/functions/src/firestore/posts/on-create/cross-post-to-devto/index.ts with the above commands. Add the following content to get started:

import * as functions from "firebase-functions";

export default functions.firestore
  .document('posts/{slug}')
  .onCreate((snapshot: functions.firestore.DocumentSnapshot,
context: functions.EventContext) => {
  console.log(`New post created with slug: ${context.params.slug}. Post: ${JSON.stringify(snapshot.data())}`)
});

Firebase automatically invokes this service whenever a new document is inserted in the posts collection. For now, all we do is print the slug and the blog post object.

Get hands-on with 1200+ tech skills courses.