Skip to content

Instantly share code, notes, and snippets.

@mlafeldt
Created August 25, 2022 09:51
Show Gist options
  • Save mlafeldt/f9a0752259e82cc91e7d7bd68248f657 to your computer and use it in GitHub Desktop.
Save mlafeldt/f9a0752259e82cc91e7d7bd68248f657 to your computer and use it in GitHub Desktop.
Talking to Clerk's backend API from Deno
#!/usr/bin/env -S deno run --allow-env=CLERK_API_KEY --allow-net=api.clerk.dev --no-check
import {
ClerkAPIResponseError,
ClerkBackendAPI,
User,
} from "https://cdn.skypack.dev/@clerk/backend-core?dts";
const ClerkAPI = new ClerkBackendAPI({
apiClient: {
// Copy-pasted from https://github.com/clerkinc/javascript/blob/main/packages/backend-core/src/__tests__/TestClerkApi.ts
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>,
...(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;
},
},
apiKey: Deno.env.get("CLERK_API_KEY"),
});
const users = await ClerkAPI.users.getUserList({ limit: 50 });
users.forEach((user: User) => {
console.log(user.id, user.username);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment