docs: Make examples ESM (#1957)

* docs: Make examples ESM

* Revert accidential change
This commit is contained in:
Aaron Dewes 2024-03-08 21:42:11 +01:00 committed by GitHub
parent b93e73aab6
commit 7583bdf293
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
15 changed files with 95 additions and 93 deletions

View File

@ -10,7 +10,7 @@ A clear and concise description of the behavior.
```js
// Your code here
module.exports = (app) => {
export default (app) => {
app.log.info("There is a bug");
};
```

View File

@ -14,7 +14,7 @@ If you've ever thought, "wouldn't it be cool if GitHub could…"; I'm going to s
**Probot is a framework for building [GitHub Apps](https://docs.github.com/en/developers/apps) in [Node.js](https://nodejs.org/)**, written in [TypeScript](https://www.typescriptlang.org/). GitHub Apps can listen to webhook events sent by a repository or organization. Probot uses its internal event emitter to perform actions based on those events. A simple Probot App might look like this:
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
const issueComment = context.issue({
body: "Thanks for opening this issue!",

View File

@ -126,11 +126,11 @@ Probot runs like [any other Node app](https://devcenter.heroku.com/articles/depl
When deploying your Probot app to a serverless/function environment, you don't need to worry about handling the http webhook requests coming from GitHub, the platform takes care of that. In many cases you can use [`createNodeMiddleware`](/docs/development/#use-createNodeMiddleware) directly, e.g. for Vercel or Google Cloud Function.
```js
const { Probot, createProbot } = require("probot");
const { createMyMiddleware } = require("my-probot-middleware");
const myApp = require("./my-app.js");
import { Probot, createProbot } from "probot";
import { createMyMiddleware } from "my-probot-middleware";
import myApp from "./my-app.js";
module.exports = createMyMiddleware(myApp, { probot: createProbot() });
export default createMyMiddleware(myApp, { probot: createProbot() });
```
For other environments such as AWS Lambda, Netlify Functions or GitHub Actions, you can use one of [Probot's adapters](https://github.com/probot/?q=adapter).
@ -139,13 +139,13 @@ For other environments such as AWS Lambda, Netlify Functions or GitHub Actions,
```js
// handler.js
const {
import {
createLambdaFunction,
createProbot,
} = require("@probot/adapter-aws-lambda-serverless");
const appFn = require("./app");
} from "@probot/adapter-aws-lambda-serverless";
import appFn from "./app.js";
module.exports.webhooks = createLambdaFunction(appFn, {
export const webhooks = createLambdaFunction(appFn, {
probot: createProbot(),
});
```
@ -166,13 +166,13 @@ Please add yours!
```js
// ProbotFunction/index.js
const {
import {
createProbot,
createAzureFunction,
} = require("@probot/adapter-azure-functions");
const app = require("../app");
} from "@probot/adapter-azure-functions";
import app from "../app.js";
module.exports = createAzureFunction(app, { probot: createProbot() });
export default createAzureFunction(app, { probot: createProbot() });
```
Learn more
@ -189,8 +189,8 @@ Please add yours!
```js
// function.js
const { createNodeMiddleware, createProbot } = require("probot");
const app = require("./app");
import { createNodeMiddleware, createProbot } from "probot";
import app from "./app.js";
exports.probotApp = createNodeMiddleware(app, { probot: createProbot() });
```
@ -204,8 +204,8 @@ Please add yours!
#### GitHub Actions
```js
const { run } = require("@probot/adapter-github-actions");
const app = require("./app");
import { run } from "@probot/adapter-github-actions";
import app from "./app.js";
run(app);
```
@ -258,7 +258,7 @@ Please add yours!
/**
* @param {import('probot').Probot} app
*/
module.exports = (app) => {
export default (app) => {
app.log("Yay! The app was loaded!");
app.on("issues.opened", async (context) => {
@ -281,11 +281,11 @@ Please add yours!
```js
// api/github/webhooks/index.js
const { createNodeMiddleware, createProbot } = require("probot");
import { createNodeMiddleware, createProbot } from "probot";
const app = require("../../../app");
import app from "../../../app.js";
module.exports = createNodeMiddleware(app, {
export default createNodeMiddleware(app, {
probot: createProbot(),
webhooksPath: "/api/github/webhooks",
});
@ -306,13 +306,13 @@ Please add yours!
```js
// functions/index.js
const {
import {
createLambdaFunction,
createProbot,
} = require("@probot/adapter-aws-lambda-serverless");
const appFn = require("../src/app");
} from "@probot/adapter-aws-lambda-serverless";
import appFn from "../src/app";
module.exports.handler = createLambdaFunction(appFn, {
export const handler = createLambdaFunction(appFn, {
probot: createProbot(),
});
```
@ -346,10 +346,10 @@ Note that this feature is only supported when [run as Node app](#as-node-app). F
```js
// app.js
const autoresponder = require("probot-autoresponder");
const settings = require("probot-settings");
import autoresponder from "probot-autoresponder";
import settings from "probot-settings";
module.exports = async (app, options) => {
export default async (app, options) => {
await autoresponder(app, options);
await settings(app, options);
};

View File

@ -159,8 +159,8 @@ If you take a look to the `npm start` script, this is what it runs: `probot run
```js
// main.js
const { run } = require("probot");
const app = require("./index.js");
import { run } from "probot";
import app from "./index.js";
// pass a probot app function
run(app);
@ -178,8 +178,8 @@ The [`run`](https://github.com/probot/probot/blob/master/src/run.ts) function th
Among other things, using the Server instance permits you to set your own [`Octokit` constructor](https://github.com/octokit/core.js) with custom plugins and a custom logger.
```js
const { Server, Probot } = require("probot");
const app = require("./index.js");
import { Server, Probot } from "probot";
import app from "./index.js";
async function startServer() {
const server = new Server({
@ -203,8 +203,8 @@ The `server` instance gives you access to the express app instance (`server.expr
If you have your own server or deploy to a serverless environment that supports loading [Express-style middleware](https://expressjs.com/en/guide/using-middleware.html) or Node's http middleware (`(request, response) => { ... }`), you can use `createNodeMiddleware`.
```js
const { createNodeMiddleware, Probot } = require("probot");
const app = require("./index.js");
import { createNodeMiddleware, Probot } from "probot";
import app from "./index.js";
const probot = new Probot({
appId: 123,
@ -212,22 +212,22 @@ const probot = new Probot({
secret: "webhooksecret123",
});
module.exports = createNodeMiddleware(app, { probot });
export default createNodeMiddleware(app, { probot });
```
If you want to read probot's configuration from the same environment variables as [`run`](#run), use the [`createProbot`](https://probot.github.io/api/latest/index.html#createprobot) export
```js
const { createNodeMiddleware, createProbot } = require("probot");
const app = require("./index.js");
import { createNodeMiddleware, createProbot } from "probot";
import app from "./index.js";
module.exports = createNodeMiddleware(app, { probot: createProbot() });
export default createNodeMiddleware(app, { probot: createProbot() });
```
By default, `createNodeMiddleware()` uses `/api/github/webhooks` as the webhook endpoint. To customize this behaviour, you can use the `webhooksPath` option.
```js
module.exports = createNodeMiddleware(app, {
export default createNodeMiddleware(app, {
probot: createProbot(),
webhooksPath: "/path/to/webhook/endpoint",
});
@ -238,8 +238,8 @@ module.exports = createNodeMiddleware(app, {
If you don't use Probot's http handling in order to receive and verify events from GitHub via webhook requests, you can use the [`Probot`](https://probot.github.io/api/latest/classes/probot.Probot.html) class directly.
```js
const { Probot } = require("probot");
const app = require("./index.js");
import { Probot } from "probot";
import app from "./index.js";
async function example() {
const probot = new Probot({
@ -266,7 +266,7 @@ Using the `Probot` class directly is great for [writing tests](/docs/testing) fo
Sometimes you may need to create your own instance of Probot's internally used [Octokit](https://github.com/octokit/rest.js/#readme) class, for example when using the [OAuth user authorization flow](https://docs.github.com/en/developers/apps/identifying-and-authorizing-users-for-github-apps). You may access the class by importing `ProbotOctokit`:
```js
const { ProbotOctokit } = require("probot");
import { ProbotOctokit } from "probot";
function myProbotApp(app) {
const octokit = new ProbotOctokit({

View File

@ -22,9 +22,9 @@ While Probot doesn't have an official extension API, there are a handful of reus
For example, users could add labels from comments by typing `/label in-progress`.
```js
const commands = require("probot-commands");
import commands from "probot-commands";
module.exports = (app) => {
export default (app) => {
// Type `/label foo, bar` in a comment box for an Issue or Pull Request
commands(app, "label", (context, command) => {
const labels = command.arguments.split(/, */);
@ -40,9 +40,9 @@ module.exports = (app) => {
For example, here is a contrived app that stores the number of times that comments were edited in a discussion and comments with the edit count when the issue is closed.
```js
const metadata = require("probot-metadata");
import metadata from "probot-metadata";
module.exports = (app) => {
export default (app) => {
app.on(["issues.edited", "issue_comment.edited"], async (context) => {
const kv = await metadata(context);
await kv.set("edits", (await kv.get("edits")) || 1);
@ -64,9 +64,9 @@ module.exports = (app) => {
[probot-attachments](https://github.com/probot/attachments) adds message attachments to comments on GitHub. This extension should be used any time an app is appending content to user comments.
```js
const attachments = require("probot-attachments");
import attachments from "probot-attachments";
module.exports = (app) => {
export default (app) => {
app.on("issue_comment.created", (context) => {
return attachments(context).add({
title: "Hello World",

View File

@ -16,7 +16,7 @@ Your Probot app has access to an authenticated [Octokit client](https://octokit.
Here is an example of an autoresponder app that comments on opened issues:
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// `context` extracts information from the event, which can be passed to
// GitHub API calls. This will return:
@ -47,7 +47,7 @@ const addComment = `
}
`;
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// Post a comment on the issue
context.octokit.graphql(addComment, {
@ -70,7 +70,7 @@ const pinIssue = `
}
`;
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
context.octokit.graphql(pinIssue, {
id: context.payload.issue.node_id,

View File

@ -8,7 +8,7 @@ title: Hello World
A Probot app is just a [Node.js module](https://nodejs.org/api/modules.html) that exports a function:
```js
module.exports = (app) => {
export default (app) => {
// your code here
};
```
@ -18,7 +18,7 @@ The `app` parameter is an instance of [`Probot`](https://probot.github.io/api/la
`app.on` will listen for any [webhook events triggered by GitHub](/docs/webhooks/), which will notify you when anything interesting happens on GitHub that your app wants to know about.
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// A new issue was opened, what should we do with it?
context.log.info(context.payload);
@ -31,7 +31,7 @@ The [`context`](https://probot.github.io/api/latest/classes/context.Context.html
Here is an example of an autoresponder app that comments on opened issues:
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// `context` extracts information from the event, which can be passed to
// GitHub API calls. This will return:

View File

@ -10,12 +10,14 @@ When starting your app using `probot run ./app.js` or using the [`Server`](/docs
Calling `getRouter('/my-app')` will return an [express](http://expressjs.com/) router that you can use to expose custom HTTP endpoints from your app.
```js
module.exports = (app, { getRouter }) => {
import * as express from "express";
export default (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"));
router.use(express.static("public"));
// Add a new route
router.get("/hello-world", (req, res) => {

View File

@ -10,7 +10,7 @@ Probot comes with [`pino`](https://getpino.io), a minimal logging library that o
`app.log`, `context.log` in an event handler, and `req.log` in an HTTP request are all loggers that you can use to get more information about what your app is doing.
```js
module.exports = (app, { getRouter }) => {
export default (app, { getRouter }) => {
app.log.info("Yay, my app is loaded");
app.on("issues.opened", (context) => {
@ -34,7 +34,7 @@ When you start up your Probot app you should see your log message appear in your
Occasionally you will want to log more detailed information that is useful for debugging, but you might not want to see it all the time.
```js
module.exports = (app) => {
export default (app) => {
// …
app.log.trace("Really low-level logging");
app.log.debug({ data: "here" }, "End-line specs on the rotary girder");
@ -63,7 +63,7 @@ When `NODE_ENV` is set (as it should be in production), the log output is struct
For example, given this log:
```js
module.exports = (app) => {
export default (app) => {
app.on("issue_comment.created", (context) => {
context.log.info("Comment created");
});

View File

@ -8,7 +8,7 @@ title: Pagination
Many GitHub API endpoints are paginated. The [`octokit.paginate` method](https://github.com/octokit/plugin-paginate-rest.js/#readme) can be used to get each page of the results.
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", (context) => {
context.octokit.paginate(
context.octokit.issues.list,
@ -28,7 +28,7 @@ module.exports = (app) => {
The return value of the `octokit.paginate` callback will be used to accumulate results.
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
const allIssues = await context.octokit.paginate(
context.octokit.issues.list,
@ -45,7 +45,7 @@ module.exports = (app) => {
Sometimes it is desirable to stop fetching pages after a certain condition has been satisfied. A second argument, `done`, is provided to the callback and can be used to stop pagination. After `done` is invoked, no additional pages will be fetched, but you still need to return the mapped value for the current page request.
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", (context) => {
context.octokit.paginate(
context.octokit.issues.list,
@ -69,7 +69,7 @@ module.exports = (app) => {
Using async iterators you can iterate through each response
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
for await (const response of octokit.paginate.iterator(
context.octokit.issues.list,

View File

@ -45,7 +45,7 @@ For when you absolutely do need external data storage, here are some examples us
```js
// PeopleSchema.js
const mongoose = require("mongoose");
import * as mongoose from "mongoose";
const Schema = mongoose.Schema;
@ -56,13 +56,13 @@ const PeopleSchema = new Schema({
},
});
module.exports = mongoose.model("People", PeopleSchema);
export default mongoose.model("People", PeopleSchema);
```
```js
// index.js
const mongoose = require("mongoose");
import * as mongoose from "mongoose";
// Connect to the Mongo database using credentials
// in your environment variables
@ -75,9 +75,9 @@ mongoose.connect(mongoUri, {
});
// Register the mongoose model
const People = require("./PeopleSchema");
import People from "./PeopleSchema.js";
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// Find all the people in the database
const people = await People.find().exec();
@ -105,20 +105,20 @@ Using the [`@databases/mysql`](https://www.atdatabases.org/docs/mysql.html) modu
```js
// connection.js
const mysql = require("@databases/mysql");
import { connect } from "@databases/mysql";
// DATABASE_URL = mysql://my-user:my-password@localhost/my-db
const connection = connect(process.env.DATABASE_URL);
module.exports = connection;
export default connection;
```
```js
// index.js
const { sql } = require("@databases/mysql");
const connection = require("./connection");
import { sql } from "@databases/mysql";
import connection from "./connection.js";
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// Find all the people in the database
const people = await connection.query(sql`SELECT * FROM people`);
@ -146,20 +146,20 @@ Using the [`@databases/pg`](https://www.atdatabases.org/docs/pg.html) module, we
```js
// connection.js
const mysql = require("@databases/pg");
import { connect } from "@databases/pg";
// DATABASE_URL = postgresql://my-user:my-password@localhost/my-db
const connection = connect(process.env.DATABASE_URL);
module.exports = connection;
export default connection;
```
```js
// index.js
const { sql } = require("@databases/pg");
const connection = require("./connection");
import { sql } from "@databases/pg";
import connection from "./connection.js";
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// Find all the people in the database
const people = await connection.query(sql`SELECT * FROM people`);
@ -188,7 +188,7 @@ module.exports = (app) => {
```js
// index.js
const firebase = require("firebase");
import * as firebase from "firebase";
// Set the configuration for your app
// TODO: Replace with your project's config object
const config = {
@ -200,7 +200,7 @@ firebase.initializeApp(config);
const database = firebase.database();
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// Find all the people in the database
const people = await database

View File

@ -10,12 +10,12 @@ We highly recommend working in the style of [test-driven development](http://agi
For our testing examples, we use [jest](https://facebook.github.io/jest/), but there are other options that can perform similar operations. We also recommend using [nock](https://github.com/nock/nock), a tool for mocking HTTP requests, which is often crucial to testing in Probot, considering how much of Probot depends on GitHub's APIs. Here's an example of creating an app instance and using nock to test that we correctly hit the GitHub API:
```js
const nock = require("nock");
import nock from "nock";
// Requiring our app implementation
const myProbotApp = require("..");
const { Probot, ProbotOctokit } = require("probot");
import myProbotApp from "../index.js";
import { Probot, ProbotOctokit } from "probot";
// Requiring our fixtures
const payload = require("./fixtures/issues.opened");
import payload from "./fixtures/issues.opened.json" with { type: "json" };
const issueCreatedBody = { body: "Thanks for opening this issue!" };
describe("My Probot app", () => {
@ -64,8 +64,8 @@ describe("My Probot app", () => {
Probot is using [pino](https://getpino.io/) for logging. A custom `pino` instance can be passed to the `Probot` constructor. You can write all log output into an array by passing a custom transport function:
```js
const pino = require("pino");
const Stream = require("stream");
import pino from "pino";
import Stream from "stream";
const streamLogsToOutput = new Stream.Writable({ objectMode: true });
streamLogsToOutput._write = (object, encoding, done) => {

View File

@ -10,7 +10,7 @@ title: Receiving webhooks
Many apps will spend their entire day responding to these actions. `app.on` will listen for any GitHub webhook events:
```js
module.exports = (app) => {
export default (app) => {
app.on("push", async (context) => {
// Code was pushed to the repo, what should we do with it?
app.log.info(context);
@ -23,7 +23,7 @@ The app can listen to any of the [GitHub webhook events](https://docs.github.com
Most events also include an "action". For example, the [`issues`](https://docs.github.com/en/developers/webhooks-and-events/webhook-events-and-payloads#issues) event has actions of `assigned`, `unassigned`, `labeled`, `unlabeled`, `opened`, `edited`, `milestoned`, `demilestoned`, `closed`, and `reopened`. Often, your app will only care about one type of action, so you can append it to the event name with a `.`:
```js
module.exports = (app) => {
export default (app) => {
app.on("issues.opened", async (context) => {
// An issue was just opened.
});
@ -33,7 +33,7 @@ module.exports = (app) => {
Sometimes you want to handle multiple webhook events the same way. `app.on` can listen to a list of events and run the same callback:
```js
module.exports = (app) => {
export default (app) => {
app.on(["issues.opened", "issues.edited"], async (context) => {
// An issue was opened or edited, what should we do with it?
app.log.info(context);
@ -44,7 +44,7 @@ module.exports = (app) => {
You can also use `app.onAny()` to listen for any event that your app is subscribed to:
```js
module.exports = (app) => {
export default (app) => {
app.onAny(async (context) => {
app.log.info({ event: context.name, action: context.payload.action });
});

View File

@ -12,7 +12,7 @@ import type { State } from "./types.js";
* to wait for the magic to happen.
*
* ```js
* module.exports = (app) => {
* export default (app) => {
* app.on('issues.opened', async context => {
* const octokit = await app.auth();
* });

View File

@ -47,7 +47,7 @@ type RepoResultType<E extends WebhookEvents> = {
* helpers for extracting information can be passed to GitHub API calls.
*
* ```js
* module.exports = app => {
* export default app => {
* app.on('push', context => {
* context.log.info('Code was pushed to the repo, what should we do with it?');
* });