Skip to content

Commit

Permalink
feat(clerk-sdk-node): Teach node-sdk to work with fetch
Browse files Browse the repository at this point in the history
Polyfill global.fetch only in Node environments if necessary and increase interoperability for the SDK across Node and V8 runtime environments.

Fixes #127
  • Loading branch information
SokratisVidros committed Jun 25, 2022
1 parent 13da4de commit 369df5c
Show file tree
Hide file tree
Showing 19 changed files with 650 additions and 717 deletions.
68 changes: 33 additions & 35 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/backend-core/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ export * from './ClerkBackendApi';
export * from './resources';
export { ClerkAPIResponseError } from './errors';

export type { APIClient } from './endpoints/AbstractApi';
export type { APIClient, APIRequestOptions } from './endpoints/AbstractApi';
export type { Session } from './resources/Session';
10 changes: 0 additions & 10 deletions packages/edge/src/constants.ts

This file was deleted.

52 changes: 38 additions & 14 deletions packages/edge/src/vercel-edge/ClerkAPI.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,46 @@
import { ClerkBackendAPI } from '@clerk/backend-core';
import { ClerkAPIResponseError, ClerkBackendAPI } from '@clerk/backend-core';

import { PACKAGE_REPO } from '../constants';
import { LIB_NAME, LIB_VERSION } from '../info';

export const ClerkAPI = new ClerkBackendAPI({
libName: LIB_NAME,
libVersion: LIB_VERSION,
packageRepo: PACKAGE_REPO,
fetcher: (url, { method, authorization, contentType, userAgent, body }) => {
return fetch(url, {
method,
headers: {
authorization: authorization,
'Content-Type': contentType,
'User-Agent': userAgent,
'X-Clerk-SDK': `vercel-edge/${LIB_VERSION}`,
},
...(body && { body: JSON.stringify(body) }),
}).then(body => (contentType === 'text/html' ? body : body.json()));
apiClient: {
async request({ url, method, queryParams, headerParams, bodyParams }) {
// Build final URL with search parameters
const finalUrl = new URL(url || '');

if (queryParams) {
for (const [key, val] of Object.entries(queryParams as Record<string, string | string[]>)) {
// Support array values for queryParams such as { foo: [42, 43] }
if (val) {
[val].flat().forEach(v => finalUrl.searchParams.append(key, v));
}
}
}

const response = await fetch(finalUrl.href, {
method,
headers: {
...(headerParams as Record<string, string>),
'X-Clerk-SDK': `vercel-edge/${LIB_VERSION}`,
},
...(bodyParams && Object.keys(bodyParams).length > 0 && { body: JSON.stringify(bodyParams) }),
});

// Parse JSON or Text response.
const isJSONResponse = headerParams && headerParams['Content-Type'] === 'application/json';
const data = await (isJSONResponse ? response.json() : response.text());

// Check for errors
if (!response.ok) {
throw new ClerkAPIResponseError(response.statusText, {
data: data?.errors || data,
status: response.status,
});
}

return data;
},
},
});
21 changes: 17 additions & 4 deletions packages/edge/src/vercel-edge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,28 @@ import { AuthStatus, Base, createGetToken, createSignedOutState } from '@clerk/b
import { ClerkJWTClaims } from '@clerk/types';
import { NextFetchEvent, NextRequest, NextResponse } from 'next/server';

import { ClerkAPI } from './ClerkAPI';
import { ClerkAPI } from './ClerkApi';
import {
AuthData,
NextMiddlewareResult,
RequestWithAuth,
WithEdgeMiddlewareAuthCallback,
WithEdgeMiddlewareAuthMiddlewareResult,
WithEdgeMiddlewareAuthOptions,
} from './types';
import { injectAuthIntoRequest } from './utils';

export function injectAuthIntoRequest(req: NextRequest, authData: AuthData): RequestWithAuth {
const { user, session, userId, sessionId, getToken, claims } = authData;
const auth = {
userId,
sessionId,
getToken,
claims,
};

/* Object.assign is used here as NextRequest properties also include Symbols */
return Object.assign(req, { auth, user, session });
}

/**
*
Expand Down Expand Up @@ -55,8 +69,7 @@ const users = ClerkAPI.users;
export { allowlistIdentifiers, clients, emails, invitations, organizations, sessions, smsMessages, users };

async function fetchInterstitial() {
const response = await ClerkAPI.fetchInterstitial<Response>();
return response.text();
return ClerkAPI.fetchInterstitial<string>();
}

export function withEdgeMiddlewareAuth<
Expand Down
1 change: 0 additions & 1 deletion packages/edge/src/vercel-edge/utils/index.ts

This file was deleted.

16 changes: 0 additions & 16 deletions packages/edge/src/vercel-edge/utils/injectAuthIntoRequest.ts

This file was deleted.

6 changes: 0 additions & 6 deletions packages/edge/vercel-edge/package.json

This file was deleted.

Loading

0 comments on commit 369df5c

Please sign in to comment.