### Install Dependencies Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/examples/cloudflare-webhook/README.md Run this command in the project directory to install necessary packages. ```bash npm install ``` -------------------------------- ### Install patreon-api.ts with yarn Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/installation.md Use this command to install the package using yarn. ```sh yarn add patreon-api.ts ``` -------------------------------- ### Install patreon-api.ts with npm, pnpm, or yarn Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/README.md Install the library using your preferred package manager. ```sh npm install patreon-api.ts pnpm add patreon-api.ts yarn add patreon-api.ts ``` -------------------------------- ### Install patreon-api.ts with npm Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/installation.md Use this command to install the package using npm. ```sh npm install patreon-api.ts ``` -------------------------------- ### Initialize Patreon Client Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/request.md Example of initializing a Patreon client with fetch options. Ensure the correct token is provided if not set globally. ```typescript import Patreon from "patreon"; const client = Patreon.default({ token: "MY_PATREON_API_TOKEN", }); ``` -------------------------------- ### Install patreon-api.ts with pnpm Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/installation.md Use this command to install the package using pnpm. ```sh pnpm add patreon-api.ts ``` -------------------------------- ### Fetch Client Example Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/index.md Demonstrates how to use the client to fetch data. Ensure all attributes are explicitly requested as per API v2. ```typescript import { Patreon } from "patreon"; const patreon = new Patreon(process.env.PATREON_CLIENT_ID as string, process.env.PATREON_CLIENT_SECRET as string); async function fetchExample() { const data = await patreon.fetch("/users/me", { includes: ["members", "campaign"], fields: { user: ["email", "full_name"], member: ["patron_status"], campaign: ["name"] } }); console.log(data); } fetchExample(); ``` -------------------------------- ### Custom Wrapper Example Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/index.md Illustrates creating a custom wrapper class for the Patreon client to include all attributes and resources by default. ```typescript import { Patreon } from "patreon"; class PatreonWrapper extends Patreon { constructor() { super(process.env.PATREON_CLIENT_ID as string, process.env.PATREON_CLIENT_SECRET as string); } async fetchAllAttributes(path: string, options?: any) { return this.fetch(path, { includes: ["members", "campaign"], fields: { user: ["email", "full_name"], member: ["patron_status"], campaign: ["name"] }, ...options }); } } const wrapper = new PatreonWrapper(); async function wrapperExample() { const data = await wrapper.fetchAllAttributes("/users/me"); console.log(data); } wrapperExample(); ``` -------------------------------- ### Initialize Patreon Oauth Client Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/request.md Example of initializing a Patreon Oauth client. This client is suitable for OAuth2 authenticated requests. ```typescript import Patreon from "patreon"; const oauthClient = Patreon.oauth({ token: "MY_PATREON_API_TOKEN", }); ``` -------------------------------- ### Fetch Raw Example Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/index.md Shows how to make a raw fetch request to the Patreon API. This method bypasses some of the client's convenience features. ```typescript import { Patreon } from "patreon"; const patreon = new Patreon(process.env.PATREON_CLIENT_ID as string, process.env.PATREON_CLIENT_SECRET as string); async function fetchRawExample() { const data = await patreon.fetchRaw("/users/me"); console.log(data); } fetchRawExample(); ``` -------------------------------- ### Fetch Campaigns Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/request.md Example of fetching a list of campaigns associated with the authenticated user. This method fetches the first page of results. ```typescript const { data } = await client.get("/campaigns"); ``` -------------------------------- ### GET /data Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/apps/api.md Returns information about resources and the Patreon API. ```APIDOC ## GET /data ### Description Returns some information about resources and the Patreon API. See the GitHub app for more details and the response body. ### Method GET ### Endpoint /data ``` -------------------------------- ### Initialize Rest Client Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/request.md Example of initializing a Rest client for Patreon API interactions. Note that this client has limitations on certain features like request pagination. ```typescript import Patreon from "patreon"; const restClient = Patreon.rest({ token: "MY_PATREON_API_TOKEN", }); ``` -------------------------------- ### Fetch Members Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/request.md Example of fetching a list of members for a campaign. Requires a campaign ID and fetches the first page of results. ```typescript const { data } = await client.get("/campaigns/{campaignId}/members"); ``` -------------------------------- ### Get Creator Token Options Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md Use this snippet to get a creator token when you don't need to handle OAuth2 requests for users. Ensure the token is stored securely for regular use. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", }); const token = oauth.token.cachedToken; console.log(token); ``` -------------------------------- ### Fetch Store for Tokens Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md Implement token storage using a fetch-based store, where an external server handles GET and PUT requests for token management. This is useful for centralized token storage. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", tokenStore: OAuth.token.fetchStore( "https://example.com/patreon-token", "https://example.com/patreon-token" ), }); await oauth.token.store(); ``` -------------------------------- ### JSON:API Payload Example Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/simplify.md This is the default JSON:API payload structure returned by the Patreon API, featuring separate fields for attributes, relationships, and included data. ```json { "data": { "type": "user", "id": "123", "attributes": { "name": "John Doe" }, "relationships": { "posts": { "data": [ { "type": "post", "id": "456" }, { "type": "post", "id": "789" } ] } } }, "included": [ { "type": "post", "id": "456", "attributes": { "title": "My First Post" } }, { "type": "post", "id": "789", "attributes": { "title": "My Second Post" } } ] } ``` -------------------------------- ### Normalized Payload Example Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/simplify.md A normalized payload combines data from `relationships` and `included` fields into a more cohesive structure, making it easier to access related resources. ```json { "data": { "type": "user", "id": "123", "attributes": { "name": "John Doe" }, "posts": [ { "type": "post", "id": "456", "attributes": { "title": "My First Post" } }, { "type": "post", "id": "789", "attributes": { "title": "My Second Post" } } ] } } ``` -------------------------------- ### Mock Agent with Cache or Random Data Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Use undici's MockAgent to intercept requests and provide mocked responses. This example shows how to configure it to use cache or random data. ```typescript import { MockAgent } from 'undici'; const agent = new MockAgent(); agent.get('https://www.patreon.com/api/oauth2/v2/resource') .intercept({ method: 'GET' }) .reply(200, { data: { id: '123', type: 'resource', attributes: { foo: 'bar' } } }); agent.cache.set('resource', [ { id: '123', type: 'resource', attributes: { foo: 'bar' } } ]); ``` -------------------------------- ### Convert Patreon Webhook Payload for Discord Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Transform the JSON:API formatted Patreon webhook payload into a format suitable for other platforms, such as Discord, when forwarding events. This example specifically converts a 'Posts published' event. ```typescript import { PayloadClient } from "@patreon/oauth/webhook"; const payloadClient = new PayloadClient(webhookData.data); const discordMessage = { content: `New post from ${payloadClient.user.attributes.full_name} published! Check it out: ${payloadClient.post.attributes.url}`, }; console.log(discordMessage); ``` -------------------------------- ### Custom Client Configuration Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/index.md Demonstrates configuring a custom Patreon client instance with specific options, such as including all queries. ```typescript import { Patreon } from "patreon"; const patreon = new Patreon(process.env.PATREON_CLIENT_ID as string, process.env.PATREON_CLIENT_SECRET as string, undefined, { includeAllQueries: true }); async function customClientExample() { const data = await patreon.fetch("/users/me"); console.log(data); } customClientExample(); ``` -------------------------------- ### Handle User OAuth2 Login with Client Options Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md Initiate the OAuth2 login flow for a user using pre-configured client options, including redirect URI and scopes. This simplifies the process when the client is already set up. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", redirectUri: "http://localhost:3000/oauth/callback", scopes: ["users.read"], }); const url = oauth.login.url(); console.log(url); ``` -------------------------------- ### Initialize API Client for Webhooks Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Instantiate the API client to interact with Patreon's webhook endpoints. Ensure you have your access token ready. ```typescript import { PatreonAPI } from "@patreon/oauth"; const api = new PatreonAPI("YOUR_ACCESS_TOKEN"); ``` -------------------------------- ### Handle User OAuth2 Login with Method Options Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md Initiate the OAuth2 login flow for a user by providing options directly to the login method. This offers flexibility when the client might not have all necessary configurations set globally. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", }); const url = oauth.login.url({ redirectUri: "http://localhost:3000/oauth/callback", scopes: ["users.read"], state: "OPTIONAL_STATE", }); console.log(url); ``` -------------------------------- ### KV Store for Tokens Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md Demonstrates using a KV (Key-Value) store for managing tokens, suitable for edge runtimes. This method allows for efficient retrieval and storage of tokens. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", tokenStore: OAuth.token.kvStore(), }); await oauth.token.store(); ``` -------------------------------- ### Fetch a Campaign Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/request.md Demonstrates how to fetch a specific campaign using the client. Ensure you have the correct campaign ID. ```typescript const { data } = await client.get("/campaigns/{campaignId}"); ``` -------------------------------- ### Create Secrets File Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/examples/cloudflare-webhook/README.md Define your API credentials and webhook details in this JSON file. Ensure sensitive information is kept secure. ```json { "CLIENT_ID": "YOUR_CLIENT_ID", "CLIENT_SECRET": "YOUR_CLIENT_SECRET", "CAMPAIGN_ID": "YOUR_CAMPAIGN_ID", "WEBHOOK_URI": "YOUR_WEBHOOK_URI", "ACCESS_TOKEN": "YOUR_ACCESS_TOKEN", "REFRESH_TOKEN": "YOUR_REFRESH_TOKEN" } ``` -------------------------------- ### Initialize Mock Cache Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Define initial items in the mock cache to provide consistent server responses. The cache holds attributes and relationships to act as a consistent server. ```typescript import { MockAgent } from 'undici'; const agent = new MockAgent(); agent.intercept({ method: 'GET', path: '/api/oauth2/v2/resource' }).reply(200, { data: { id: '123', type: 'resource', attributes: { foo: 'bar' } } }); // Initialize cache agent.cache.set('resource', [ { id: '123', type: 'resource', attributes: { foo: 'bar' } } ]); ``` -------------------------------- ### POST /proxy/{path} Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/apps/api.md A simple proxy with CORS headers to the Patreon API. Forwards the body, headers, and method. ```APIDOC ## POST /proxy/{path} ### Description A simple proxy with CORS headers to the patreon API. Forwards the body, headers and method. Replace `{path}` with the route of the Patreon API route: `https://patreon.com/api/oauth2/v2/campaigns` becomes `/proxy/campaigns`. ### Method POST ### Endpoint /proxy/{path} ### Parameters #### Path Parameters - **path** (string) - Required - The route of the Patreon API route to proxy. ``` -------------------------------- ### Fetch Campaign Data with QueryBuilder Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/README.md Use QueryBuilder to specify attributes for fetching campaign data. The client.fetchCampaign method returns a detailed response, while client.simplified.fetchCampaign provides a more concise object. ```typescript const query = QueryBuilder.campaign .setAttributes({ campaign: ['patron_count'] }) const payload = await client.fetchCampaign('campaign_id', query) // ^? { data: { attributes: { patron_count: number } }, ... } const campaign = await client.simplified.fetchCampaign('campaign_id', query) // ^? { patronCount: number, id: string, type: Type.Campaign } ``` -------------------------------- ### Store Creator Token Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md This snippet demonstrates how to store a creator token, which is recommended due to token expiration. The token should be synced to a database or a safe storage location. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", token: "YOUR_CREATOR_TOKEN", }); // Store the token in your database or a safe place await oauth.token.store(); ``` -------------------------------- ### Create a New Webhook Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Create a new webhook for a specific campaign, defining the triggers and the URI where events should be posted. Requires campaign ID, URI, and a list of triggers. ```typescript const newWebhook = await api.webhooks.create({ campaign_id: "YOUR_CAMPAIGN_ID", uri: "https://example.com/patreon-webhook", triggers: ["pledge:create", "pledge:delete"], }); console.log(newWebhook); ``` -------------------------------- ### Initialize User OAuth Client Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md Initialize the OAuth client for user authentication, including the redirect URI and necessary scopes. The client will not cache or store tokens automatically for user OAuth2 requests. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", redirectUri: "http://localhost:3000/oauth/callback", scopes: ["users.read", "identity[email]"], }); ``` -------------------------------- ### Generate Access Token Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/examples/cloudflare-webhook/README.md Run this script to generate necessary tokens for API authentication. It may require `ts-node` or prior compilation. ```typescript import { PatreonAPI } from "patreon-api.ts"; const api = new PatreonAPI({ clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, campaignId: process.env.CAMPAIGN_ID, webhookUri: process.env.WEBHOOK_URI, accessToken: process.env.ACCESS_TOKEN, refreshToken: process.env.REFRESH_TOKEN, }); async function generateTokens() { const tokens = await api.getTokens(); console.log(tokens); } generateTokens(); ``` -------------------------------- ### Deploy Cloudflare Worker Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/examples/cloudflare-webhook/README.md Use this command to deploy the Cloudflare Worker to your account. ```bash npm run deploy ``` -------------------------------- ### Paginate Campaigns Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/request.md Shows how to paginate through campaign results. This method leverages the client's pagination capabilities to fetch subsequent pages. ```typescript const campaigns = await client.paginate("/campaigns"); for await (const campaign of campaigns) { // process campaign } ``` -------------------------------- ### Fetch User Token with Code Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md After a user is redirected back to your application, use the provided 'code' query parameter to fetch the user's access token. This method is used when handling the callback from Patreon's login. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", redirectUri: "http://localhost:3000/oauth/callback", }); const token = await oauth.token.fetch("AUTHORIZATION_CODE"); console.log(token); ``` -------------------------------- ### Custom Store for Tokens Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md Allows for a fully custom token storage solution by providing your own implementation of token retrieval and storage methods. This offers maximum flexibility. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", tokenStore: { get: async () => { // Your custom get logic }, put: async (token) => { // Your custom put logic }, }, }); await oauth.token.store(); ``` -------------------------------- ### Include All Queries - patreon-api.ts Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/configuration.md Configure the client to include all relationships and attributes by default, instead of empty attributes. This affects the response type for all requests. ```typescript import Patreon from 'patreon-api.ts'; const patreon = new Patreon(process.env.PATREON_TOKEN, { rest: { includeAllQueries: true } }); ``` ```typescript import Patreon from 'patreon-api.ts'; const patreon = new Patreon(process.env.PATREON_TOKEN, { rest: { includeAllQueries: false } }); ``` -------------------------------- ### Fetch All Webhooks Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Retrieve a list of all webhooks associated with your application. This is useful for monitoring or managing existing webhooks. ```typescript const webhooks = await api.webhooks.list(); console.log(webhooks); ``` -------------------------------- ### Paginate Members Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/request.md Demonstrates paginating through members of a campaign. This method allows for iterating over all members across multiple pages. ```typescript const members = await client.paginate("/campaigns/{campaignId}/members"); for await (const member of members) { // process member } ``` -------------------------------- ### Configure Event Emitter - patreon-api.ts Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/configuration.md Connect an event emitter to listen to rest events such as 'request', 'response', or 'ratelimit'. ```typescript import Patreon from 'patreon-api.ts'; const patreon = new Patreon(process.env.PATREON_TOKEN, { rest: { emitter: console } }); ``` -------------------------------- ### Mock Service Worker All Routes Handler Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Configure Mock Service Worker to handle all routes with a default response. This is useful for setting up a general mock server. ```typescript import { rest } from 'msw'; const allHandlers = [ rest.get('/api/*', (req, res, ctx) => { return res( ctx.status(200), ctx.json({ message: 'Default response' }) ); }) ]; ``` -------------------------------- ### Mock Service Worker Route Handler Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Set up a route handler using Mock Service Worker (MSW) to intercept specific API requests. This allows for granular control over mocked responses. ```typescript import { rest } from 'msw'; const handler = rest.get('/api/user/:id', (req, res, ctx) => { return res( ctx.status(200), ctx.json({ id: req.params.id, name: 'John Doe' }) ); }); ``` -------------------------------- ### Enable Request Validation Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Enable validation for request paths, headers, and query parameters to ensure mocked requests are valid. This will throw an error if validation fails. ```typescript import { MockAgent } from 'undici'; const agent = new MockAgent(); // Enable request validation agent.assert = true; // ... rest of your mocking setup ``` -------------------------------- ### Create Random Resource Data Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Generate random resource data for API responses. This uses a simple random data generator, and it's recommended to use a library like faker-js for more complex needs. Each attribute is generated independently. ```typescript import { MockAgent } from 'undici'; const agent = new MockAgent(); agent.get('https://www.patreon.com/api/oauth2/v2/resource') .intercept({ method: 'GET' }) .reply(200, { data: { id: '123', type: 'resource', attributes: { // ... random attributes } } }); ``` -------------------------------- ### Add Relationships to Mocked Resource Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Define included items to add relationships to a mocked API response. This allows for simulating nested data structures. ```typescript import { MockAgent } from 'undici'; const agent = new MockAgent(); agent.get('https://www.patreon.com/api/oauth2/v2/resource') .intercept({ method: 'GET' }) .reply(200, { data: { id: '123', type: 'resource', attributes: { // ... attributes }, relationships: { // ... relationships } }, included: [ // ... included resources ] }); ``` -------------------------------- ### Simplify Method - TypeScript Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/simplify.md Use the `simplify` method to normalize the response and convert all keys to camelCase. This method can be accessed directly via `client.simplified`. ```typescript import { api } from "@patreon/api"; const client = api(); const response = await client.simplified.get("/users/me"); console.log(response); ``` -------------------------------- ### Mock Fetch Function for Testing Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Use `rest.fetch` with a mocked function to intercept API calls in unit tests without using MockAgent. This is useful for testing API or OAuth2 responses. ```typescript import { rest } from 'vitest'; const mockFn = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: 'mocked response' }) }); // Use mockFn to mock fetch calls ``` -------------------------------- ### Verify Incoming Webhook Request Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Verify the authenticity of an incoming webhook request from Patreon using the request body, headers, and your webhook's secret. This is crucial for security. ```typescript import { verifyWebhook } from "@patreon/oauth/webhook"; const isValid = await verifyWebhook(request, { secret: "YOUR_WEBHOOK_SECRET", }); if (!isValid) { // Handle invalid request return; } // Process valid request ``` -------------------------------- ### Query Method - TypeScript Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/simplify.md The `query` method allows fetching and processing data using a simplified response format directly. This is useful when dealing with typed queries. ```typescript import { api } from "@patreon/api"; const client = api(); const response = await client.query("/users/me", { simplify: true, }); console.log(response); ``` -------------------------------- ### Parse and Verify Webhook Request Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Use the `parseWebhookRequest` utility to simultaneously verify the request and parse its JSON payload. It requires the request object, the webhook secret, and optionally the expected event type. ```typescript import { parseWebhookRequest } from "@patreon/oauth/webhook"; const webhookData = await parseWebhookRequest(request, { secret: "YOUR_WEBHOOK_SECRET", }); console.log(webhookData); ``` -------------------------------- ### Mock Agent with Custom Response Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Configure MockAgent to return a custom response for intercepted requests. This allows for precise control over the mocked API behavior. ```typescript import { MockAgent } from 'undici'; const agent = new MockAgent(); agent.get('https://www.patreon.com/api/oauth2/v2/resource') .intercept({ method: 'GET' }) .reply(200, { data: { id: '123', type: 'resource', attributes: { foo: 'bar' } } }); ``` -------------------------------- ### Use Payload Client for Webhook Data Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Access common attributes like campaign or user directly from the webhook payload using the payload client. This simplifies data extraction. ```typescript import { PayloadClient } from "@patreon/oauth/webhook"; const payloadClient = new PayloadClient(webhookData.data); const campaign = payloadClient.campaign; const user = payloadClient.user; console.log(campaign, user); ``` -------------------------------- ### Custom Parser Registration - TypeScript Declaration Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/simplify.md Register custom response parsers using module augmentation for `ResponseTransformMap`. This allows you to define specific transformations for API responses, such as adding custom attributes. ```typescript import type { PatreonAPI } from "@patreon/api"; declare module "@patreon/api" { interface ResponseTransformMap { campaign_id: (response: PatreonAPI.GetResponsePayload) => string; } } // Example usage: // const response = await client.custom.get("/some/endpoint", { // transform: { campaign_id: () => "12345" }, // }); ``` -------------------------------- ### Mock Service Worker Error Handler Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/sandbox.md Implement an error handler using Mock Service Worker to simulate API errors. This allows testing how your application handles failed requests. ```typescript import { rest } from 'msw'; const errorHandler = [ rest.get('/api/error', (req, res, ctx) => { return res( ctx.status(500), ctx.json({ error: 'Internal Server Error' }) ); }) ]; ``` -------------------------------- ### Unpause a Paused Webhook Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Resume a webhook that has been automatically paused due to sending failures. Set the `paused` attribute to `false` to unpause. ```typescript const unpausedWebhook = await api.webhooks.update("YOUR_WEBHOOK_ID", { paused: false, }); console.log(unpausedWebhook); ``` -------------------------------- ### Refresh Access Token Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/oauth.md Refresh an expired access token using the `refreshToken` method. This will update the cached token and also update the token store if one is configured. ```typescript import OAuth from "@/oauth"; const oauth = new OAuth({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", token: "YOUR_EXPIRED_REFRESH_TOKEN", }); await oauth.token.refreshToken(); console.log(oauth.token.cachedToken); ``` -------------------------------- ### Update an Existing Webhook Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Modify the triggers and URI of an existing webhook. Use the webhook's ID to specify which webhook to update. ```typescript const updatedWebhook = await api.webhooks.update("YOUR_WEBHOOK_ID", { uri: "https://example.com/patreon-webhook-updated", triggers: ["pledge:create", "pledge:update"], }); console.log(updatedWebhook); ``` -------------------------------- ### Parse and Verify Specific Webhook Event Type Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md When your webhook is configured for a single event type, you can pass this type as a generic parameter to `parseWebhookRequest` for more specific type safety. ```typescript import { parseWebhookRequest } from "@patreon/oauth/webhook"; import { PledgeCreateEvent } from "@patreon/oauth/types"; const webhookData = await parseWebhookRequest(request, { secret: "YOUR_WEBHOOK_SECRET", }); console.log(webhookData); ``` -------------------------------- ### Module Augmentation for Custom Types - patreon-api.ts Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/configuration.md Patch Patreon resources using TypeScript module augmentation to override fields. This is useful for undocumented features or custom type definitions. ```typescript // ./@types/patreon-api.d.ts import 'patreon-api.ts' declare module 'patreon-api.ts' { interface CustomTypeOptions { social_connections: Record } } ``` -------------------------------- ### Normalize Method - TypeScript Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/simplify.md The `normalize` method restructures the JSON:API response by merging `relationships` and `included` data. Access it via `client.normalized`. ```typescript import { api } from "@patreon/api"; const client = api(); const response = await client.normalized.get("/users/me"); console.log(response); ``` -------------------------------- ### Delete a Webhook Source: https://github.com/ghostrider-05/patreon-api.ts/blob/main/docs/guide/features/webhooks.md Remove a webhook using its unique ID. This action is irreversible. ```typescript await api.webhooks.delete("YOUR_WEBHOOK_ID"); console.log("Webhook deleted successfully."); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.