Model answer
/**
* Small GoCardless API client for Node.js 18+.
* Supports creating a payment and retrieving/listing payments.
*/
class GoCardlessClient {
constructor({ accessToken, baseUrl = "https://api.gocardless.com", timeoutMs = 10_000 }) {
if (!accessToken) throw new Error("accessToken is required");
this.accessToken = accessToken;
this.baseUrl = baseUrl.replace(/\/$/, "");
this.timeoutMs = timeoutMs;
}
async request(path, { method = "GET", query, body, idempotencyKey } = {}) {
const url = new URL(`${this.baseUrl}${path}`);
for (const [key, value] of Object.entries(query || {})) {
if (value !== undefined && value !== null) url.searchParams.set(key, String(value));
}
// Retry transient failures only when repeating the request is safe.
const retryable = method === "GET" || Boolean(idempotencyKey);
const maxAttempts = retryable ? 3 : 1;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
try {
const headers = {
Authorization: `Bearer ${this.accessToken}`,
Accept: "application/json",
};
if (body !== undefined) headers["Content-Type"] = "application/json";
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
const response = await fetch(url, {
method,
headers,
body: body === undefined ? undefined : JSON.stringify(body),
signal: controller.signal,
});
const text = await response.text();
const data = text ? JSON.parse(text) : null;
if (response.ok) return data;
const error = new Error(
data?.error?.message || `API request failed with HTTP ${response.status}`
);
error.status = response.status;
error.details = data?.error;
const transient = response.status === 429 || response.status >= 500;
if (!transient || attempt === maxAttempts - 1) throw error;
const retryAfter = Number(response.headers.get("retry-after"));
const delayMs = retryAfter > 0
? retryAfter * 1000
: 200 * 2 ** attempt + Math.random() * 100;
await new Promise((resolve) => setTimeout(resolve, delayMs));
} catch (error) {
const transientNetworkError = error.name === "AbortError" || !error.status;
if (!retryable || !transientNetworkError || attempt === maxAttempts - 1) throw error;
await new Promise((resolve) => setTimeout(resolve, 200 * 2 ** attempt + Math.random() * 100));
} finally {
clearTimeout(timer);
}
}
}
async createPayment(payment, { idempotencyKey } = {}) {
const result = await this.request("/payments", {
method: "POST",
body: { payments: payment },
idempotencyKey,
});
return result.payments;
}
async getPayment(paymentId) {
const result = await this.request(`/payments/${encodeURIComponent(paymentId)}`);
return result.payments;
}
async listPayments({ limit = 50, after, before, status } = {}) {
const result = await this.request("/payments", {
query: { limit, after, before, status },
});
return { payments: result.payments, cursors: result.meta?.cursors || {} };
}
}
// Example:
// const client = new GoCardlessClient({ accessToken: process.env.GC_TOKEN });
// const payment = await client.createPayment(
// { amount: 2500, currency: "GBP", links: { mandate: "MD123" } },
// { idempotencyKey: "invoice-456-payment" }
// );
- Keep credentials outside source control; production clients should also validate inputs and redact tokens from logs.
- Retries are bounded, and payment creation is retried only with an idempotency key to avoid duplicate charges.
- Complexity: Each request is O(response size) time and space; retries are bounded to three attempts.