From dc3ba277a86718bcc1d603ecd580ec7a2ddd414c Mon Sep 17 00:00:00 2001 From: Asher Gomez Date: Sat, 9 Sep 2023 18:18:49 +1000 Subject: [PATCH] chore: add `getGitHubUser()` JSDocs and test (#545) TSIA --- plugins/kv_oauth.ts | 32 +++++++++++++++++++++++++++----- plugins/kv_oauth_test.ts | 11 +++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) create mode 100644 plugins/kv_oauth_test.ts diff --git a/plugins/kv_oauth.ts b/plugins/kv_oauth.ts index bb85950856d0..519c30d7ea2c 100644 --- a/plugins/kv_oauth.ts +++ b/plugins/kv_oauth.ts @@ -18,8 +18,27 @@ import { isStripeEnabled, stripe } from "@/utils/stripe.ts"; const oauth2Client = createGitHubOAuth2Client(); -// deno-lint-ignore no-explicit-any -async function getGitHubUser(accessToken: string): Promise { +interface GitHubUser { + login: string; + email: string; +} + +/** + * Returns the GitHub profile information of the user with the given access + * token. + * + * @see {@link https://docs.github.com/en/rest/users/users?apiVersion=2022-11-28#get-the-authenticated-user} + * + * @example + * ```ts + * import { getGitHubUser } from "@/plugins/kv_oauth.ts"; + * + * const user = await getGitHubUser(""); + * user.login; // Returns "octocat" + * user.email; // Returns "octocat@github.com" + * ``` + */ +export async function getGitHubUser(accessToken: string) { const response = await fetch("https://api.github.com/user", { headers: { authorization: `Bearer ${accessToken}` }, }); @@ -27,13 +46,16 @@ async function getGitHubUser(accessToken: string): Promise { const { message } = await response.json(); throw new Error(message); } - return await response.json(); + return await response.json() as Promise; } /** - * This custom plugin centralizes all authentication logic using the {@link https://deno.land/x/deno_kv_oauth|Deno KV OAuth} module. + * This custom plugin centralizes all authentication logic using the + * {@link https://deno.land/x/deno_kv_oauth|Deno KV OAuth} module. * - * The implementation is based off Deno KV OAuth's own {@link https://deno.land/x/deno_kv_oauth/src/fresh_plugin.ts?source|Fresh plugin implementation}. + * The implementation is based off Deno KV OAuth's own + * {@link https://deno.land/x/deno_kv_oauth/src/fresh_plugin.ts?source|Fresh plugin} + * implementation. */ export default { name: "kv-oauth", diff --git a/plugins/kv_oauth_test.ts b/plugins/kv_oauth_test.ts new file mode 100644 index 000000000000..8d6cd2f2f63e --- /dev/null +++ b/plugins/kv_oauth_test.ts @@ -0,0 +1,11 @@ +// Copyright 2023 the Deno authors. All rights reserved. MIT license. +import { assertRejects } from "std/assert/assert_rejects.ts"; +import { getGitHubUser } from "./kv_oauth.ts"; + +Deno.test("[plugins] getGitHubUser()", async () => { + await assertRejects( + async () => await getGitHubUser("access token"), + Error, + "Bad credentials", + ); +});