Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rest): Add unique user-agent to requests #45

Merged
merged 1 commit into from
Oct 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion packages/rest/src/__tests__/interceptors.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@ import { vol } from 'memfs';

import * as rateLimitModule from '../rateLimit';
import { Cache, generatePredictableKey } from '../cache';
import { cacheInvalidationRequestInterceptor, rateLimitRequestInterceptor } from '../interceptors';
import {
cacheInvalidationRequestInterceptor,
rateLimitRequestInterceptor,
userAgentRequestInterceptor,
} from '../interceptors';
import { Basic200 } from '../__fixtures__/storage';
import { Client } from '../client';
import { fileRequest } from '../__fixtures__/fileRequest';
Expand Down Expand Up @@ -71,6 +75,21 @@ describe('@figmarine/rest - interceptors', () => {
vi.restoreAllMocks();
});

describe('userAgentRequestInterceptor', () => {
it('returns a function when called', () => {
const interceptor = userAgentRequestInterceptor();
expect(typeof interceptor).toBe('function');
});

it('adds a User-Agent header containing the client and runtime names', async () => {
const interceptor = userAgentRequestInterceptor();

expect(fileRequest.headers['User-Agent']).toMatch(/^axios\//);
interceptor(fileRequest);
expect(fileRequest.headers['User-Agent']).toMatch(/^figmarine-rest\/git/);
});
});

describe('cacheInvalidationRequestInterceptor', () => {
it('returns a function when called', ({ cache }) => {
const interceptor = cacheInvalidationRequestInterceptor(cache);
Expand Down
9 changes: 8 additions & 1 deletion packages/rest/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { log } from '@figmarine/logger';

import { Api, type Api as ApiInterface } from './__generated__/figmaRestApi';
import { Cache, type ClientCacheOptions } from './cache';
import { cacheInvalidationRequestInterceptor, rateLimitRequestInterceptor } from './interceptors';
import {
cacheInvalidationRequestInterceptor,
rateLimitRequestInterceptor,
userAgentRequestInterceptor,
} from './interceptors';
import { get429Config } from './rateLimit.config';
import { securityWorker } from './securityWorker';

Expand Down Expand Up @@ -140,6 +144,9 @@ export async function Client(opts: ClientOptions = {}): Promise<ClientInterface>
});
}

/* Add User-Agent header to all requests. */
api.instance.interceptors.request.use(userAgentRequestInterceptor());

log(`Created Figma REST API client successfully.`);

return {
Expand Down
58 changes: 58 additions & 0 deletions packages/rest/src/interceptors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,64 @@ import { log } from '@figmarine/logger';

import { Cache, generatePredictableKey } from './cache';
import { interceptRequest } from './rateLimit';
import manifest from '../package.json';

function detectRuntime(): string {
if (typeof globalThis === 'undefined') {
return 'Unknown runtime (likely legacy)';
}

if ('Netlify' in globalThis) {
return 'netlify';
}

if ('__lagon__' in globalThis) {
return 'lagon';
}

if ('EdgeRuntime' in globalThis) {
return 'edge-light';
}

if ('fastly' in globalThis) {
return 'fastly';
}

// @ts-expect-error Runtime dependant global.
if ('Deno' in globalThis && globalThis.Deno.version.deno) {
// @ts-expect-error Runtime dependant global.
return `deno v${globalThis.Deno.version.deno}`;
}

// @ts-expect-error Runtime dependant global.
if ('Bun' in globalThis && globalThis.Bun.version) {
// @ts-expect-error Runtime dependant global.
return `bun v${globalThis.Bun.version}`;
}

if ('process' in globalThis && globalThis.process.versions?.node) {
return `node v${process.versions.node}`;
}

if ('window' in globalThis) {
return 'Browser';
}

return 'unknown';
}

export function userAgentRequestInterceptor() {
const runtime = detectRuntime();
const version = manifest.version.startsWith('0.0.0') ? 'git' : manifest.version;
const userAgent = `figmarine-rest/${version} (${runtime} runtime)`;
log(`Detected User-Agent: ${userAgent}.`);

return function (config: InternalAxiosRequestConfig) {
config.headers = config.headers || {};
config.headers['User-Agent'] = userAgent;
return config;
};
}

export function cacheInvalidationRequestInterceptor(cache: Cache) {
return async function (config: InternalAxiosRequestConfig) {
Expand Down