import { MosaicError, MosaicErrors } from '@axinom/mosaic-service-common'; import { getGqlClient } from '../common/gql-client'; import { IdLinkBeErrors } from '../common/id-link-be-errors'; import { DevCreateServiceAccountDocument, DevCreateServiceAccountMutation, DevCreateServiceAccountMutationVariables, } from '../generated/graphql.types'; import { getWellKnownEndpoints } from '../well-known-endpoints'; /** Development service account information */ export interface DevServiceAccount { clientId: string; clientSecret: string; serviceAccountName: string; } /** * This function creates a new service account which can be used during development. * @param authEndpoint URL for id-service authEndpoint. * @param serviceAccountName Name of the service account. * @param permissions The list of permissions to be assigned to the service account. This is an array of shape { serviceId: string, permissions: string[] }. * @returns {DevServiceAccount} New development service account information. */ export const devCreateServiceAccount = async ( authEndpoint: string, serviceId: string, serviceAccountName: string, tenantId: string, environmentId: string, permissions: { serviceId: string; permissions?: string[]; }[], ): Promise => { const client = getGqlClient( (await getWellKnownEndpoints(authEndpoint)).authGraphQlEndpoint, 'Bearer token-not-needed-for-DEV-endpoints', ); const result = await client.mutate< DevCreateServiceAccountMutation, DevCreateServiceAccountMutationVariables >({ mutation: DevCreateServiceAccountDocument, variables: { input: { serviceAccountName, tenantId, environmentId: environmentId, permissionStructure: permissions, }, }, errorPolicy: 'all', fetchPolicy: 'no-cache', }); if (!result.errors) { if (result.data?._DEV_createServiceAccount) { return result.data._DEV_createServiceAccount; } throw new MosaicError({ code: MosaicErrors.UnexpectedNullUndefined.code, message: `Unexpected null or undefined value received for '_DEV_createServiceAccount' result.`, }); } else { const aggregatedErrorMessage = result.errors.reduce( (aggregatedError, gqlError) => { return (aggregatedError += gqlError.message); }, '', ); throw new MosaicError({ ...IdLinkBeErrors.ServiceAccountCreateError, details: { originalError: aggregatedErrorMessage, }, }); } };