From af4a2ed3be9e6790a46a22c88092d7321cbd3e0a Mon Sep 17 00:00:00 2001 From: Hongbo Wu Date: Mon, 6 Jun 2022 11:46:00 +0800 Subject: [PATCH] Add generateApiKey mutation in Web --- .../mutations/generateApiKeyMutation.ts | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 packages/web/lib/networking/mutations/generateApiKeyMutation.ts diff --git a/packages/web/lib/networking/mutations/generateApiKeyMutation.ts b/packages/web/lib/networking/mutations/generateApiKeyMutation.ts new file mode 100644 index 000000000..d8c531001 --- /dev/null +++ b/packages/web/lib/networking/mutations/generateApiKeyMutation.ts @@ -0,0 +1,47 @@ +import { gql } from 'graphql-request' +import { gqlFetcher } from '../networkHelpers' +import { ApiKey } from '../queries/useGetApiKeysQuery' + +export interface GenerateApiKeyInput { + name: string + scopes?: string[] + expiresAt: Date +} + +interface GenerateApiKeyResult { + generateApiKey: GenerateApiKey + errorCodes?: unknown[] +} + +type GenerateApiKey = { + apiKey: ApiKey +} + +export async function generateApiKeyMutation( + input: GenerateApiKeyInput +): Promise { + const mutation = gql` + mutation GenerateApiKey($input: GenerateApiKeyInput!) { + generateApiKey(input: $input) { + ... on GenerateApiKeySuccess { + apiKey { + key + } + } + ... on GenerateApiKeyError { + errorCodes + } + } + } + ` + + try { + const data = (await gqlFetcher(mutation, { + input, + })) as GenerateApiKeyResult + return data.errorCodes ? undefined : data.generateApiKey.apiKey.key + } catch (error) { + console.log('generateApiKeyMutation error', error) + return undefined + } +}