### Example 1 - Dispatch GET request
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Dispatcher.md
An example demonstrating how to dispatch a GET request and handle the response using callbacks.
```APIDOC
## GET / Example
### Description
This example demonstrates dispatching a GET request and handling the response using callbacks.
### Method
GET
### Endpoint
/
### Request Example
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
const data = []
client.dispatch({
path: '/',
method: 'GET',
headers: {
'x-foo': 'bar'
}
}, {
onConnect: () => {
console.log('Connected!')
},
onError: (error) => {
console.error(error)
},
onHeaders: (statusCode, headers) => {
console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`)
},
onData: (chunk) => {
console.log('onData: chunk received')
data.push(chunk)
},
onComplete: (trailers) => {
console.log(`onComplete | trailers: ${trailers}`)
const res = Buffer.concat(data).toString('utf8')
console.log(`Data: ${res}`)
client.close()
server.close()
}
})
```
### Response
#### Success Response (200)
- **body** (string) - The response body, e.g., 'Hello, World!'.
#### Response Example
```json
{
"example": "Hello, World!"
}
```
```
--------------------------------
### Perform a Basic GET Request
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Dispatcher.md
This example demonstrates how to perform a basic GET request using the `Dispatcher.request` method. It sets up a local HTTP server, makes a request to it, and logs the response status, headers, and body. Ensure the server and client are closed after the request.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { body, headers, statusCode, trailers } = await client.request({
path: '/',
method: 'GET'
})
console.log(`response received ${statusCode}`)
console.log('headers', headers)
body.setEncoding('utf8')
body.on('data', console.log)
body.on('end', () => {
console.log('trailers', trailers)
})
client.close()
server.close()
} catch (error) {
console.error(error)
}
```
--------------------------------
### Dispatch GET Request with Undici
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Dispatcher.md
This example demonstrates how to dispatch a GET request using Undici. It includes setting up a mock server, creating a client, and defining handlers for connection, errors, headers, data, and completion. Ensure the server and client are properly closed after the request.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
const data = []
client.dispatch({
path: '/',
method: 'GET',
headers: {
'x-foo': 'bar'
}
}, {
onConnect: () => {
console.log('Connected!')
},
onError: (error) => {
console.error(error)
},
onHeaders: (statusCode, headers) => {
console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`)
},
onData: (chunk) => {
console.log('onData: chunk received')
data.push(chunk)
},
onComplete: (trailers) => {
console.log(`onComplete | trailers: ${trailers}`)
const res = Buffer.concat(data).toString('utf8')
console.log(`Data: ${res}`)
client.close()
server.close()
}
})
```
--------------------------------
### Install @actions/http-client
Source: https://github.com/homebrew/actions/blob/main/node_modules/@actions/http-client/README.md
Install the @actions/http-client package using npm.
```bash
npm install @actions/http-client --save
```
--------------------------------
### Create token auth with Installation or Action token
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/auth-token/README.md
Use createTokenAuth with an installation access token or a GITHUB_TOKEN from GitHub Actions. The resulting object will have tokenType 'installation'.
```javascript
createTokenAuth("ghs_InstallallationOrActionToken00000000");
// {
// type: 'token',
// token: 'ghs_InstallallationOrActionToken00000000',
// tokenType: 'installation'
// }
```
--------------------------------
### Clone and Install Project Dependencies
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/graphql-schema/README.md
Standard procedure for setting up the project locally. Clone the repository, navigate into the directory, and install npm dependencies.
```bash
git clone https://github.com/octokit/graphql-schema.git
cd graphql-schema
npm install
npm test
```
--------------------------------
### Make an HTTP request with undici
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/README.md
This example demonstrates how to make a GET request to a local server and process the response. It shows how to access status codes, headers, and stream the response body. Ensure a server is running on http://localhost:3000/foo before executing.
```javascript
import { request } from 'undici'
const {
statusCode,
headers,
trailers,
body
} = await request('http://localhost:3000/foo')
console.log('response received', statusCode)
console.log('headers', headers)
for await (const data of body) { console.log('data', data) }
console.log('trailers', trailers)
```
--------------------------------
### Install fast-content-type-parse
Source: https://github.com/homebrew/actions/blob/main/node_modules/fast-content-type-parse/README.md
Install the package using npm.
```sh
$ npm install fast-content-type-parse
```
--------------------------------
### Get Installation Token
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/core/README.md
Obtain an installation access token using the authenticated app Octokit instance. This token is specific to a particular installation of the GitHub App.
```javascript
const { token } = await appOctokit.auth({
type: "installation",
installationId: 123,
});
```
--------------------------------
### Installation
Source: https://github.com/homebrew/actions/blob/main/node_modules/fast-content-type-parse/README.md
Install the fast-content-type-parse package using npm.
```APIDOC
## Installation
```sh
$ npm install fast-content-type-parse
```
```
--------------------------------
### Install GraphQL.js with npm
Source: https://github.com/homebrew/actions/blob/main/node_modules/graphql/README.md
Install the GraphQL.js library using npm for your project.
```sh
npm install --save graphql
```
--------------------------------
### Mock Request with Path Callback
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/MockPool.md
This example demonstrates mocking a GET request to 'http://localhost:3000/foo?foo=bar' using a callback function to match the request path and query parameters. Ensure the 'undici' and 'querystring' modules are imported.
```javascript
import { MockAgent, setGlobalDispatcher, request } from 'undici'
import querystring from 'querystring'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
const matchPath = requestPath => {
const [pathname, search] = requestPath.split('?')
const requestQuery = querystring.parse(search)
if (!pathname.startsWith('/foo')) {
return false
}
if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') {
return false
}
return true
}
mockPool.intercept({
path: matchPath,
method: 'GET'
}).reply(200, 'foo')
const result = await request('http://localhost:3000/foo?foo=bar')
// Will match and return mocked data
```
--------------------------------
### Install GraphQL.js with yarn
Source: https://github.com/homebrew/actions/blob/main/node_modules/graphql/README.md
Install the GraphQL.js library using yarn for your project.
```sh
yarn add graphql
```
--------------------------------
### Install Dependencies for All Actions
Source: https://github.com/homebrew/actions/blob/main/README.md
Run this command in the root directory to install or update dependencies for all Homebrew Actions.
```bash
npm install
```
--------------------------------
### Example - Basic RetryHandler with defaults
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/RetryHandler.md
Demonstrates how to create a RetryHandler instance using default retry configurations.
```APIDOC
### Request Example
```javascript
const client = new Client(`http://localhost:${server.address().port}`);
const handler = new RetryHandler(dispatchOptions, {
dispatch: client.dispatch.bind(client),
handler: {
onConnect() {},
onBodySent() {},
onHeaders(status, _rawHeaders, resume, _statusMessage) {},
onData(chunk) {},
onComplete() {},
onError(err) {},
},
});
```
```
--------------------------------
### ProxyAgent Usage Examples
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/ProxyAgent.md
Examples demonstrating how to use ProxyAgent for making proxied requests.
```APIDOC
### Example - Basic ProxyAgent instantiation
This will instantiate the ProxyAgent. It will not do anything until registered as the agent to use with requests.
```javascript
import { ProxyAgent } from 'undici'
const proxyAgent = new ProxyAgent('my.proxy.server')
```
### Example - Basic Proxy Request with global agent dispatcher
Registers the ProxyAgent as the global dispatcher for all undici requests.
```javascript
import { setGlobalDispatcher, request, ProxyAgent } from 'undici'
const proxyAgent = new ProxyAgent('my.proxy.server')
setGlobalDispatcher(proxyAgent)
const { statusCode, body } = await request('http://localhost:3000/foo')
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
### Example - Basic Proxy Request with local agent dispatcher
Uses a ProxyAgent instance for a specific request.
```javascript
import { ProxyAgent, request } from 'undici'
const proxyAgent = new ProxyAgent('my.proxy.server')
const { statusCode, body } = await request('http://localhost:3000/foo', { dispatcher: proxyAgent })
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
### Example - Basic Proxy Request with authentication
Configures the ProxyAgent with authentication credentials.
```javascript
import { setGlobalDispatcher, request, ProxyAgent } from 'undici';
const proxyAgent = new ProxyAgent({
uri: 'my.proxy.server',
// token: 'Bearer xxxx'
token: `Basic ${Buffer.from('username:password').toString('base64')}`
});
setGlobalDispatcher(proxyAgent);
const { statusCode, body } = await request('http://localhost:3000/foo');
console.log('response received', statusCode); // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')); // data foo
}
```
```
--------------------------------
### NPM Installation
Source: https://github.com/homebrew/actions/blob/main/node_modules/json-with-bigint/README.md
Install the json-with-bigint library using npm for use in your Node.js or browser projects.
```bash
npm i json-with-bigint
```
--------------------------------
### Connect Request with Echo - Undici Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Dispatcher.md
Demonstrates establishing a two-way communication channel using HTTP CONNECT and echoing data back to the client. This example requires setting up a mock HTTP server that handles the CONNECT method.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
throw Error('should never get here')
}).listen()
server.on('connect', (req, socket, head) => {
socket.write('HTTP/1.1 200 Connection established\r\n\r\n')
let data = head.toString()
socket.on('data', (buf) => {
data += buf.toString()
})
socket.on('end', () => {
socket.end(data)
})
})
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { socket } = await client.connect({
path: '/'
})
const wanted = 'Body'
let data = ''
socket.on('data', d => { data += d })
socket.on('end', () => {
console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`)
client.close()
server.close()
})
socket.write(wanted)
socket.end()
} catch (error) { }
```
--------------------------------
### Install @octokit/request in Node.js
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/request/README.md
Install the @octokit/request library using npm for use in Node.js projects.
```bash
npm install @octokit/request
```
--------------------------------
### JS-YAML Installation
Source: https://github.com/homebrew/actions/blob/main/node_modules/js-yaml/README.md
Instructions for installing JS-YAML via npm for both Node.js module usage and CLI executable.
```APIDOC
## Installation
### YAML module for node.js
```bash
npm install js-yaml
```
### CLI executable
If you want to inspect your YAML files from CLI, install js-yaml globally:
```bash
npm install -g js-yaml
```
#### Usage
```
usage: js-yaml [-h] [-v] [-c] [-t] file
Positional arguments:
file File with YAML document(s)
Optional arguments:
-h, --help Show this help message and exit.
-v, --version Show program's version number and exit.
-c, --compact Display errors in compact mode
-t, --trace Show stack trace on error
```
```
--------------------------------
### Usage Examples
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/auth-token/README.md
Demonstrates how to import and use the createTokenAuth function in both browser and Node.js environments.
```APIDOC
## Usage
### Browsers
Load `@octokit/auth-token` directly from [esm.sh](https://esm.sh)
```html
```
### Node.js
Install with `npm install @octokit/auth-token`
```js
import { createTokenAuth } from "@octokit/auth-token";
```
```js
const auth = createTokenAuth("ghp_PersonalAccessToken01245678900000000");
const authentication = await auth();
// {
// type: 'token',
// token: 'ghp_PersonalAccessToken01245678900000000',
// tokenType: 'oauth'
// }
```
```
--------------------------------
### Install undici with npm
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/README.md
Install the undici package using npm. This is the first step to using undici in your Node.js project.
```bash
npm i undici
```
--------------------------------
### Simple hookCollection Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/before-after-hook/README.md
A basic example demonstrating how to use hookCollection with a single hook name and a callback function.
```javascript
hookCollection(
"save",
(record) => {
return store.save(record);
},
record
);
// shorter: hookCollection('save', store.save, record)
```
--------------------------------
### Using Token for Git Operations
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/auth-token/README.md
Demonstrates how to use authentication tokens for Git operations, including prefixing installation tokens.
```APIDOC
## Use token for git operations
Both OAuth and installation access tokens can be used for git operations. For installation tokens, the token must be prefixed with `x-access-token`.
This example uses the `execa` package to run a `git push` command.
```js
const TOKEN = "ghp_PersonalAccessToken01245678900000000";
const auth = createTokenAuth(TOKEN);
const { token, tokenType } = await auth();
const tokenWithPrefix =
tokenType === "installation" ? `x-access-token:${token}` : token;
const repositoryUrl = `https://${tokenWithPrefix}@github.com/octocat/hello-world.git`;
const { stdout } = await execa("git", ["push", repositoryUrl]);
console.log(stdout);
```
```
--------------------------------
### Set up Ruby with Bundler Cache
Source: https://github.com/homebrew/actions/blob/main/setup-ruby/README.md
Enable the Bundler cache for faster gem installations. This requires Homebrew to be set up and will cache the 'vendor/bundle' directory.
```yaml
- name: Set up Ruby with Bundler cache
uses: Homebrew/actions/setup-ruby@main
with:
setup-homebrew: true
bundler-cache: true
```
--------------------------------
### EnvHttpProxyAgent Usage Examples
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/EnvHttpProxyAgent.md
Demonstrates how to use EnvHttpProxyAgent with undici's fetch and request methods, both globally and locally.
```APIDOC
### Example - Basic Proxy Fetch with global agent dispatcher
```js
import { setGlobalDispatcher, fetch, EnvHttpProxyAgent } from 'undici'
const envHttpProxyAgent = new EnvHttpProxyAgent()
setGlobalDispatcher(envHttpProxyAgent)
const { status, json } = await fetch('http://localhost:3000/foo')
console.log('response received', status) // response received 200
const data = await json() // data { foo: "bar" }
```
### Example - Basic Proxy Request with global agent dispatcher
```js
import { setGlobalDispatcher, request, EnvHttpProxyAgent } from 'undici'
const envHttpProxyAgent = new EnvHttpProxyAgent()
setGlobalDispatcher(envHttpProxyAgent)
const { statusCode, body } = await request('http://localhost:3000/foo')
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
### Example - Basic Proxy Request with local agent dispatcher
```js
import { EnvHttpProxyAgent, request } from 'undici'
const envHttpProxyAgent = new EnvHttpProxyAgent()
const { statusCode, body } = await request('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent })
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
### Example - Basic Proxy Fetch with local agent dispatcher
```js
import { EnvHttpProxyAgent, fetch } from 'undici'
const envHttpProxyAgent = new EnvHttpProxyAgent()
const { status, json } = await fetch('http://localhost:3000/foo', { dispatcher: envHttpProxyAgent })
console.log('response received', status) // response received 200
const data = await json() // data { foo: "bar" }
```
```
--------------------------------
### Instantiate MockAgent
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/MockAgent.md
Instantiates the MockAgent. This is the basic setup before registering it and adding mock interceptions.
```javascript
import { MockAgent } from 'undici'
const mockAgent = new MockAgent()
```
--------------------------------
### Import Octokit in Node.js
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/core/README.md
Install @octokit/core using npm and import the Octokit class for Node.js environments.
```javascript
import { Octokit } from "@octokit/core";
```
--------------------------------
### Typing Webhook Payloads with @octokit/webhooks-definitions
Source: https://github.com/homebrew/actions/blob/main/node_modules/@actions/github/README.md
Install and use type definitions from @octokit/webhooks-definitions to get better type information for webhook payloads. This example shows how to type a 'push' event payload.
```typescript
import * as core from '@actions/core'
import * as github from '@actions/github'
import {PushEvent} from '@octokit/webhooks-definitions/schema'
if (github.context.eventName === 'push') {
const pushPayload = github.context.payload as PushEvent
core.info(`The head commit is: ${pushPayload.head_commit}`)
}
```
--------------------------------
### Implement Client Certificate Authentication
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/best-practices/client-certificate.md
This example demonstrates setting up an HTTPS server that requests client certificates and a client that presents its certificate for authentication. Ensure certificate files are correctly placed and named.
```javascript
const { readFileSync } = require('node:fs')
const { join } = require('node:path')
const { createServer } = require('node:https')
const { Client } = require('undici')
const serverOptions = {
ca: [
readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8')
],
key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'),
cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'),
requestCert: true,
rejectUnauthorized: false
}
const server = createServer(serverOptions, (req, res) => {
// true if client cert is valid
if(req.client.authorized === true) {
console.log('valid')
} else {
console.error(req.client.authorizationError)
}
res.end()
})
server.listen(0, function () {
const tls = {
ca: [
readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8')
],
key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'),
cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'),
rejectUnauthorized: false,
servername: 'agent1'
}
const client = new Client(`https://localhost:${server.address().port}`, {
connect: tls
})
client.request({
path: '/',
method: 'GET'
}, (err, { body }) => {
body.on('data', (buf) => {})
body.on('end', () => {
client.close()
server.close()
})
})
})
```
--------------------------------
### Basic DNS Interceptor Setup
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Dispatcher.md
Demonstrates how to set up and use the DNS interceptor with a client. Ensure you replace `...opts` with your desired DNS interceptor configuration and `requestOpts` with your request options.
```javascript
const { Client, interceptors } = require("undici");
const { dns } = interceptors;
const client = new Agent().compose([
dns({ ...opts })
])
const response = await client.request({
origin: `http://localhost:3030`,
...requestOpts
})
```
--------------------------------
### Basic GET Stream Request
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Dispatcher.md
Example of performing a GET request and streaming the response body directly to a Writable stream. The `opaque` option is used to pass data to the stream factory.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
import { Writable } from 'stream'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
const bufs = []
try {
await client.stream({
path: '/',
method: 'GET',
opaque: { bufs }
}, ({ statusCode, headers, opaque: { bufs } }) => {
console.log(`response received ${statusCode}`)
console.log('headers', headers)
return new Writable({
write (chunk, encoding, callback) {
bufs.push(chunk)
callback()
}
})
})
console.log(Buffer.concat(bufs).toString('utf-8'))
client.close()
server.close()
} catch (error) {
console.error(error)
}
```
--------------------------------
### Define multiple hooks at once
Source: https://github.com/homebrew/actions/blob/main/node_modules/before-after-hook/README.md
Example showing how to define hooks for multiple names ('add', 'save') simultaneously, with a common callback and options.
```javascript
hookCollection(
["add", "save"],
(record) => {
return store.save(record);
},
record
);
```
--------------------------------
### Client Constructor
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Client.md
Initializes a new Client instance. The URL should only include the protocol, hostname, and port.
```APIDOC
## new Client(url[, options])
### Description
Initializes a new Client instance.
### Parameters
#### Path Parameters
* **url** (URL | string) - Required - Should only include the **protocol, hostname, and port**.
* **options** (ClientOptions) - Optional - Configuration options for the client.
### Returns
`Client` - An instance of the Client class.
```
--------------------------------
### Basic Argument Parsing Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/argparse/README.md
This script demonstrates how to set up an ArgumentParser, add arguments with help messages, and parse them. It includes version and help flags. Use this for standard CLI argument handling.
```javascript
#!/usr/bin/env node
'use strict';
const { ArgumentParser } = require('argparse');
const { version } = require('./package.json');
const parser = new ArgumentParser({
description: 'Argparse example'
});
parser.add_argument('-v', '--version', { action: 'version', version });
parser.add_argument('-f', '--foo', { help: 'foo bar' });
parser.add_argument('-b', '--bar', { help: 'bar foo' });
parser.add_argument('--baz', { help: 'baz bar' });
console.dir(parser.parse_args());
```
--------------------------------
### Usage with NPM Import
Source: https://github.com/homebrew/actions/blob/main/node_modules/json-with-bigint/README.md
Import and use `JSONParse` and `JSONStringify` after installing via npm. This example shows storing and retrieving data with BigInt from localStorage.
```javascript
import { JSONParse, JSONStringify } from 'json-with-bigint';
const userData = {
someBigNumber: 9007199254740992n
};
localStorage.setItem('userData', JSONStringify(userData));
const restoredUserData = JSONParse(localStorage.getItem('userData') || '');
```
--------------------------------
### Basic Fetch Request
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/README.md
Demonstrates the basic usage of the fetch function to make a GET request and parse the JSON response. Ensure 'undici' is installed.
```javascript
import { fetch } from 'undici'
const res = await fetch('https://example.com')
const json = await res.json()
console.log(json)
```
--------------------------------
### Mocking Requests with Path Callback
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/MockPool.md
This example demonstrates how to mock an HTTP GET request using a custom path matching function that checks both the pathname and query parameters.
```APIDOC
## MockPool Intercept with Path Callback
### Description
Intercepts HTTP requests with a dynamic path matching function.
### Method
GET
### Endpoint
/foo?foo=bar
### Parameters
#### Query Parameters
- **foo** (string) - Required - Must be 'bar'
### Request Example
```js
import { MockAgent, setGlobalDispatcher, request } from 'undici'
import querystring from 'querystring'
const mockAgent = new MockAgent()
setGlobalDispatcher(mockAgent)
const mockPool = mockAgent.get('http://localhost:3000')
const matchPath = requestPath => {
const [pathname, search] = requestPath.split('?')
const requestQuery = querystring.parse(search)
if (!pathname.startsWith('/foo')) {
return false
}
if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') {
return false
}
return true
}
mockPool.intercept({
path: matchPath,
method: 'GET'
}).reply(200, 'foo')
const result = await request('http://localhost:3000/foo?foo=bar')
// Will match and return mocked data
```
### Response
#### Success Response (200)
- **body** (string) - The mocked response body.
#### Response Example
```
foo
```
```
--------------------------------
### Set up Ruby with Existing Homebrew
Source: https://github.com/homebrew/actions/blob/main/setup-ruby/README.md
Use this snippet to set up Ruby when Homebrew is already installed in your workflow. It first ensures Homebrew is set up and then proceeds to set up Ruby.
```yaml
- name: Set up Homebrew
uses: Homebrew/actions/setup-homebrew@main
- name: Set up Ruby
uses: Homebrew/actions/setup-ruby@main
```
--------------------------------
### MockPool Request Interception
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/MockPool.md
This example demonstrates mocking a GET request to '/foo' using MockPool.intercept and then making the request using mockPool.request. It shows how to access the status code and body of the mocked response.
```javascript
import { MockAgent } from 'undici'
const mockAgent = new MockAgent()
const mockPool = mockAgent.get('http://localhost:3000')
mockPool.intercept({
path: '/foo',
method: 'GET',
}).reply(200, 'foo')
const {
statusCode,
body
} = await mockPool.request({
origin: 'http://localhost:3000',
path: '/foo',
method: 'GET'
})
console.log('response received', statusCode) // response received 200
for await (const data of body) {
console.log('data', data.toString('utf8')) // data foo
}
```
--------------------------------
### Build Project
Source: https://github.com/homebrew/actions/blob/main/node_modules/@actions/http-client/README.md
Build the project using npm.
```bash
npm run build
```
--------------------------------
### Set up Homebrew GitHub Action
Source: https://github.com/homebrew/actions/blob/main/setup-homebrew/README.md
Use this action to set up a Homebrew environment on your GitHub Actions runner. It runs on `ubuntu` and `macos`.
```yaml
name: Set up Homebrew
id: set-up-homebrew
uses: Homebrew/actions/setup-homebrew@main
```
--------------------------------
### Example Request Options Output
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/endpoint/README.md
The resulting request options object, which includes method, URL, and headers, ready to be passed to an HTTP client.
```json
{
"method": "GET",
"url": "https://api.github.com/orgs/octokit/repos?type=private",
"headers": {
"accept": "application/vnd.github.v3+json",
"authorization": "token 0000000000000000000000000000000000000001",
"user-agent": "octokit/endpoint.js v1.2.3"
}
}
```
--------------------------------
### Usage Example for Git Try Push Action
Source: https://github.com/homebrew/actions/blob/main/git-try-push/README.md
Configure the Homebrew/actions/git-try-push action with your repository details, authentication token, and desired retry count.
```yaml
- name: Try pushing
uses: Homebrew/actions/git-try-push@main
with:
token: ${{github.token}}
directory: path/to/repo
remote: origin
branch: main
tries: 20
```
--------------------------------
### Display Help Message
Source: https://github.com/homebrew/actions/blob/main/node_modules/argparse/README.md
This shows the expected output when the -h or --help flag is used with the example script. It lists all available arguments and their descriptions.
```bash
$ ./test.js -h
usage: test.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ]
Argparse example
optional arguments:
-h, --help show this help message and exit
-v, --version show program's version number and exit
-f FOO, --foo FOO foo bar
-b BAR, --bar BAR bar foo
--baz BAZ baz bar
```
--------------------------------
### Cache Homebrew Prefix with Install List
Source: https://github.com/homebrew/actions/blob/main/cache-homebrew-prefix/README.md
Use this snippet to cache the Homebrew prefix and install specified formulae. Ensure that either 'install' or 'brewfile' is provided, but not both. The 'workflow-key' can be used to scope caches for different workflows.
```yaml
- name: Cache Homebrew prefix
uses: Homebrew/actions/cache-homebrew-prefix@main
with:
install: wget jq
uninstall: true
workflow-key: actionlint
```
--------------------------------
### Test Action Locally
Source: https://github.com/homebrew/actions/blob/main/README.md
To test an action locally, first install dependencies in the repository root, then navigate to the action's directory and run the main script. Input variables are set via environment variables.
```bash
node main.js
```
--------------------------------
### Client Instantiation
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Client.md
Demonstrates how to instantiate the undici Client. The client connects to the origin when requests are made or explicitly via `client.connect`.
```APIDOC
## Client Instantiation
### Description
Instantiates the undici Client. Connection to the origin is deferred until a request is queued or `client.connect` is called.
### Request Example
```javascript
'use strict'
import { Client } from 'undici'
const client = new Client('http://localhost:3000')
```
```
--------------------------------
### Install JS-YAML for Node.js
Source: https://github.com/homebrew/actions/blob/main/node_modules/js-yaml/README.md
Install the js-yaml package using npm for use in Node.js projects.
```bash
npm install js-yaml
```
--------------------------------
### Create Custom Octokit with Plugins and Defaults
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/core/README.md
Use this pattern to build a reusable Octokit client with specific plugins and default configurations. Ensure necessary plugins and authentication strategies are imported.
```javascript
import { Octokit } from "@octokit/core";
import { paginateRest } from "@octokit/plugin-paginate-rest";
import { throttling } from "@octokit/plugin-throttling";
import { retry } from "@octokit/plugin-retry";
import { createActionAuth } from "@octokit/auth-action";
const MyActionOctokit = Octokit.plugin(
paginateRest,
throttling,
retry,
).defaults({
throttle: {
onAbuseLimit: (retryAfter, options) => {
/* ... */
},
onRateLimit: (retryAfter, options) => {
/* ... */
},
},
authStrategy: createActionAuth,
userAgent: `my-octokit-action/v1.2.3`,
});
const octokit = new MyActionOctokit();
const installations = await octokit.paginate("GET /app/installations");
```
--------------------------------
### JSONStringify Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/json-with-bigint/README.md
Example of using `JSONStringify` to serialize a JavaScript object that includes a BigInt value.
```javascript
JSONStringify({
someBigNumber: 9007199254740992n
})
```
--------------------------------
### JSONParse Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/json-with-bigint/README.md
Example of using `JSONParse` to deserialize a JSON string that contains a BigInt value.
```javascript
JSONParse('{"someBigNumber":9007199254740992}')
```
--------------------------------
### Install JS-YAML CLI
Source: https://github.com/homebrew/actions/blob/main/node_modules/js-yaml/README.md
Install the js-yaml package globally using npm to use its command-line interface.
```bash
npm install -g js-yaml
```
--------------------------------
### List organization repositories (Alternative Options)
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/request/README.md
Alternative method to list organization repositories by passing 'method' and 'url' as part of the options object.
```javascript
const result = await request({
method: "GET",
url: "/orgs/{org}/repos",
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
});
```
--------------------------------
### Using Request Options with Got Library
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/endpoint/README.md
Illustrates how to use the generated request options with the 'got' HTTP client library.
```javascript
// using with got (https://github.com/sindresorhus/got)
got[options.method](url, options);
```
--------------------------------
### Set up Ruby from a Specific Subdirectory
Source: https://github.com/homebrew/actions/blob/main/setup-ruby/README.md
Configure the action to operate within a specific subdirectory of your project. This is useful for monorepos or projects with complex directory structures.
```yaml
- name: Set up Ruby from subdirectory
uses: Homebrew/actions/setup-ruby@main
with:
setup-homebrew: true
working-directory: path/to/project
```
--------------------------------
### Install Bleeding Edge GraphQL.js
Source: https://github.com/homebrew/actions/blob/main/node_modules/graphql/README.md
Install the latest not-yet-released version of GraphQL.js directly from the 'npm' branch of the GitHub repository.
```sh
npm install graphql@git://github.com/graphql/graphql-js.git#npm
```
--------------------------------
### Parse Arguments Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/argparse/README.md
This demonstrates how the script parses provided command-line arguments and returns them as an object. The output reflects the values passed for each argument.
```bash
$ ./test.js -f=3 --bar=4 --baz 5
{ foo: '3', bar: '4', baz: '5' }
```
--------------------------------
### Install tslib with JSPM
Source: https://github.com/homebrew/actions/blob/main/node_modules/tslib/README.md
Install the tslib library using JSPM. Choose the appropriate version based on your TypeScript version.
```sh
# TypeScript 3.9.2 or later
jspm install tslib
```
```sh
# TypeScript 3.8.4 or earlier
jspm install tslib@^1
```
```sh
# TypeScript 2.3.2 or earlier
jspm install tslib@1.6.1
```
--------------------------------
### Install tslib with bower
Source: https://github.com/homebrew/actions/blob/main/node_modules/tslib/README.md
Install the tslib library using bower. Choose the appropriate version based on your TypeScript version.
```sh
# TypeScript 3.9.2 or later
bower install tslib
```
```sh
# TypeScript 3.8.4 or earlier
bower install tslib@^1
```
```sh
# TypeScript 2.3.2 or earlier
bower install tslib@1.6.1
```
--------------------------------
### Install tslib with yarn
Source: https://github.com/homebrew/actions/blob/main/node_modules/tslib/README.md
Install the tslib library using yarn. Choose the appropriate version based on your TypeScript version.
```sh
# TypeScript 3.9.2 or later
yarn add tslib
```
```sh
# TypeScript 3.8.4 or earlier
yarn add tslib@^1
```
```sh
# TypeScript 2.3.2 or earlier
yarn add tslib@1.6.1
```
--------------------------------
### Instantiate Octokit with Pagination Plugin
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/plugin-paginate-rest/README.md
Create an Octokit instance and apply the paginateRest plugin to enable pagination capabilities. Authentication is required.
```javascript
const MyOctokit = Octokit.plugin(paginateRest);
const octokit = new MyOctokit({ auth: "secret123" });
```
--------------------------------
### Install tslib with npm
Source: https://github.com/homebrew/actions/blob/main/node_modules/tslib/README.md
Install the tslib library using npm. Choose the appropriate version based on your TypeScript version.
```sh
# TypeScript 3.9.2 or later
npm install tslib
```
```sh
# TypeScript 3.8.4 or earlier
npm install tslib@^1
```
```sh
# TypeScript 2.3.2 or earlier
npm install tslib@1.6.1
```
--------------------------------
### Install Homebrew Bundler RubyGems
Source: https://github.com/homebrew/actions/blob/main/setup-homebrew/README.md
Install Homebrew Bundler RubyGems if the cache was not hit. This command is run only when the cache for RubyGems is not found.
```yaml
name: Install Homebrew Bundler RubyGems
if: steps.cache.outputs.cache-hit != 'true'
run: brew install-bundler-gems
```
--------------------------------
### Request Aborted on Client Destroy - Undici Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Dispatcher.md
Demonstrates how pending requests are asynchronously aborted when the Undici client is destroyed. This example requires setting up a mock HTTP server.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end()
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const request = client.request({
path: '/',
method: 'GET'
})
client.destroy()
.then(() => {
console.log('Client destroyed')
server.close()
})
await request
} catch (error) {
console.error(error)
}
```
--------------------------------
### Example of using composePaginateRest with PaginatingEndpoints
Source: https://github.com/homebrew/actions/blob/main/node_modules/@octokit/plugin-paginate-rest/README.md
This example demonstrates how to define a generic `myPaginatePlugin` function in TypeScript that utilizes `composePaginateRest` and leverages `PaginatingEndpoints` for type safety when calling paginated API endpoints.
```typescript
import { Octokit } from "@octokit/core";
import {
PaginatingEndpoints,
composePaginateRest,
} from "@octokit/plugin-paginate-rest";
type DataType = "data" extends keyof T ? T["data"] : unknown;
async function myPaginatePlugin(
octokit: Octokit,
endpoint: E,
parameters?: PaginatingEndpoints[E]["parameters"],
): Promise> {
return await composePaginateRest(octokit, endpoint, parameters);
}
```
--------------------------------
### GraphQL Query AST Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/graphql-tag/README.md
An example of the Abstract Syntax Tree (AST) generated by the gql tag for a GraphQL query. This structure represents the parsed query, useful for introspection or manipulation.
```javascript
{
"kind": "Document",
"definitions": [
{
"kind": "OperationDefinition",
"operation": "query",
"name": null,
"variableDefinitions": null,
"directives": [],
"selectionSet": {
"kind": "SelectionSet",
"selections": [
{
"kind": "Field",
"alias": null,
"name": {
"kind": "Name",
"value": "user",
...
}
}
]
}
}
]
}
```
--------------------------------
### Connect to Upstream Server via Proxy (With Auth)
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/best-practices/proxy.md
This example demonstrates connecting to an upstream server through a proxy that requires basic authentication. The `proxy-authorization` header is included in the request, and the proxy server is configured to validate this header.
```javascript
import { Client } from 'undici'
import { createServer } from 'http'
import { createProxy } from 'proxy'
const server = await buildServer()
const proxyServer = await buildProxy()
const serverUrl = `http://localhost:${server.address().port}`
const proxyUrl = `http://localhost:${proxyServer.address().port}`
proxyServer.authenticate = function (req) {
return req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}`
}
server.on('request', (req, res) => {
console.log(req.url) // '/hello?foo=bar'
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify({ hello: 'world' }))
})
const client = new Client(proxyUrl)
const response = await client.request({
method: 'GET',
path: serverUrl + '/hello?foo=bar',
headers: {
'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}`
}
})
response.body.setEncoding('utf8')
let data = ''
for await (const chunk of response.body) {
data += chunk
}
console.log(response.statusCode) // 200
console.log(JSON.parse(data)) // { hello: 'world' }
server.close()
proxyServer.close()
client.close()
function buildServer () {
return new Promise((resolve, reject) => {
const server = createServer()
server.listen(0, () => resolve(server))
})
}
function buildProxy () {
return new Promise((resolve, reject) => {
const server = createProxy(createServer())
server.listen(0, () => resolve(server))
})
}
```
--------------------------------
### Set up Ruby and Homebrew Together
Source: https://github.com/homebrew/actions/blob/main/setup-ruby/README.md
This configuration sets up both Homebrew and Ruby in a single step. It's useful when Homebrew is not guaranteed to be present in the workflow.
```yaml
- name: Set up Ruby and Homebrew
uses: Homebrew/actions/setup-ruby@main
with:
setup-homebrew: true
```
--------------------------------
### Request Resolves Before Client Closes - Undici Example
Source: https://github.com/homebrew/actions/blob/main/node_modules/undici/docs/docs/api/Dispatcher.md
Illustrates a scenario where an HTTP request completes successfully before the Undici client is explicitly closed. This example requires setting up a mock HTTP server.
```javascript
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end('undici')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
try {
const { body } = await client.request({
path: '/',
method: 'GET'
})
body.setEncoding('utf8')
body.on('data', console.log)
} catch (error) {}
await client.close()
console.log('Client closed')
server.close()
```