Develop the Integration with DEV

Get an introduction to DEV and learn how to develop the integration with DEV.

DEV

First things first, what is DEV? Their About DEV page states:

"DEV is a community of software developers getting together to help one another out."

It’s a place where anyone can create an account and share their blog posts, engage in discussions, or simply tag along to see what’s going on in the developer community. As a registered user, you can write blog posts in Markdown on their website. Alternatively, they provide a REST API. The API provides a number of endpoints, and the one we are interested in is called “Create a new article”.

Note: If you want to publish your blog post to another service and they offer an API, feel free to use this chapter as a guide and adjust the code snippets to match the other service’s API.

If you don’t have an account yet, please create one at https://dev.to first.

Developing the integration with DEV

Note: All paths below are relative to services/web/firebase/functions.

To send the HTTP request to the API endpoint, we are going to use the got package, which is an HTTP library for nodejs. Click “Run” and in the terminal, install got and the latest node TypeScript types needed with:

npm i -S got

To make got work with TypeScript, we also need to provide the node types so it can compile correctly.

npm i -D @types/node

Open ./src/firestore/posts/on-create/cross-post-to-devto/index.ts and replace the file’s content with the following code. This will guide you in creating a post and using the dev.to’s API to publish the blog content on the website.

import * as functions from "firebase-functions";
import got from "got";

// Our basic Blog Post struct
interface IBlogPost {
  title: string;
  content: string;
}

// Function that takes input in the form of IBlogPost and publishes the blog content to dev.to using its API
const publishToDevto = (blogPost: IBlogPost) => got.post("https://dev.to/api/articles", {
  headers: {
    "api-key": functions.config().crossposttodevto.apikey
  },
  json: {
    article: {
      title: blogPost.title,
      body_markdown: blogPost.content,
      published: false
    }
  }
});


export default functions.firestore
  .document("posts/{slug}")
  .onCreate(
    // Creating snapshot of the post and printing it on the console
    async (
      snapshot: functions.firestore.DocumentSnapshot,
      context: functions.EventContext
    ) => {
      const blogPost = snapshot.data() as IBlogPost || {};
      console.log(
        `Posting to dev.to... Slug: ${
        context.params.slug
        }. Post: ${JSON.stringify(blogPost)}`
      );
      // Publishing & handling errors
      try {
        await publishToDevto(blogPost);
        console.log("Blog post successfully posted to dev.to.");
      } catch (error) {
        console.error(error);
      }
    }
  );

Click Run to save the changes.

Get hands-on with 1200+ tech skills courses.