How add Probot HTTP routes in Typescript?

426 views Asked by At

I'm having a hard time writing custom HTTP routes on my probot written in Typescript.

The only example in documentation is pure JS but I couldn't figure out how to translate it to TS.

 module.exports = (app, { getRouter }) => {
  // Get an express router to expose new HTTP endpoints
  const router = getRouter("/my-app");

  // Use any middleware
  router.use(require("express").static("public"));

  // Add a new route
  router.get("/hello-world", (req, res) => {
    res.send("Hello World");
  });
};

https://probot.github.io/docs/http/

3

There are 3 answers

0
Tobias S. On BEST ANSWER

This should do the trick:

import { ApplicationFunctionOptions, Probot, } from "probot"

export default (app: Probot, { getRouter }: ApplicationFunctionOptions) => {

  if (!getRouter) return

  const router = getRouter("/my-app");

  router.use(require("express").static("public"));

  // Add a new route
  router.get("/hello-world", (req, res) => {
    res.send("Hello World");
  });
}

In ApplicationFunctionOptions getRouter is optional. That's why i added a quick check in the beginning of the function.

0
Igor Medeiros On

I managed to get it working with:

import {ApplicationFunctionOptions, Probot} from "probot";


export = (app: Probot, { getRouter }: ApplicationFunctionOptions) => {

  // Get an express router to expose new HTTP endpoints
  if (getRouter) {
    const router = getRouter()
    // Use any middleware
    router.use(require("express").static("public"));

    // Add a new route
    // @ts-ignore
    router.get("/hello-world", (req: any, res: any) => {
      res.send("Hello World");
    });
  }

  app.on("issues.opened", async (context) => {
    const issueComment = context.issue({
      body: "Thanks for opening this issue!",
    });
    await context.octokit.issues.createComment(issueComment);
  });
...
0
Paulo Eduardo On

You could use axios.

For example:

import axios from "axios"

export class GithubServices {

    public async writeCommentPR(repositoryName: string, numberPR: number, comment: string) {

        try {
            const url = `https://api.github.com/repos/${repositoryName}/issues/${numberPR}/comments`
            
            const options = {
                headers: {
                    Authorization: process.env.GITHUB_PAT || "",
                    Accept: 'application/vnd.github.v3+json',
                    ContentType: "application/json"
                }
            }

            const payload = {
                "body": comment
            };

            const response = await axios.post(
                url,
                payload,
                options
            )

        } catch (error) {
            console.log(error)
        }
    }