How to write an Octokit plugin
mainAn Octokit plugin is a function with the following signature:
const plugin = (octokit, options) => { ... }
Key Capabilities:
- Hook into the request lifecycle: Use
octokit.hook.wrap(name, callback)to intercept and modify requests or responses. For example, wrapping"request"allows you to log timing or modify headers. - Add custom methods: Return an object from the plugin function. The keys in this object become new methods available on the
octokitinstance. - Access configuration: The second argument (
options) is the configuration object passed to the constructor when the client is instantiated.
It is recommended to use octokit.log methods within plugins to assist users with debugging.
const plugin = (octokit, options = { greeting: "Hello" }) => {
// 1. Hook into the request lifecycle
octokit.hook.wrap("request", async (request, options) => {
const time = Date.now();
const response = await request(options);
octokit.log.info(`${options.method} ${options.url} – ${response.status} in ${Date.now() - time}ms`);
return response;
});
// 2. Add a custom method
return {
helloWorld: () => console.log(`${options.greeting}, world!`),
};
};
export default plugin;