omnivore/packages/web/lib/networking/mutations/optIntoFeatureMutation.ts

78 lines
1.6 KiB
TypeScript
Raw Permalink Normal View History

2024-03-19 02:12:49 +00:00
import { gql } from 'graphql-request'
2024-03-28 07:27:37 +00:00
import { Feature, featureFragment } from '../fragments/featureFragment'
2024-03-19 02:12:49 +00:00
import { gqlFetcher } from '../networkHelpers'
export enum OptInFeatureErrorCode {
BadRequest = 'BAD_REQUEST',
Ineligible = 'INELIGIBLE',
NotFound = 'NOT_FOUND',
}
export type OptInResult = {
feature?: Feature
ineligible?: boolean
}
2024-03-19 02:12:49 +00:00
export interface OptInFeatureInput {
name: string
}
interface OptInFeatureResponse {
2024-03-28 07:27:37 +00:00
feature?: Feature
errorCodes?: OptInFeatureErrorCode[]
2024-03-19 02:12:49 +00:00
}
interface Response {
2024-03-28 07:27:37 +00:00
optInFeature: OptInFeatureResponse
2024-03-19 02:12:49 +00:00
}
export async function optInFeature(
input: OptInFeatureInput
): Promise<OptInResult> {
2024-03-19 02:12:49 +00:00
const mutation = gql`
mutation OptInFeature($input: OptInFeatureInput!) {
optInFeature(input: $input) {
... on OptInFeatureSuccess {
feature {
2024-03-28 07:27:37 +00:00
...FeatureFields
2024-03-19 02:12:49 +00:00
}
}
... on OptInFeatureError {
errorCodes
}
}
}
2024-03-28 07:27:37 +00:00
${featureFragment}
2024-03-19 02:12:49 +00:00
`
try {
const data = await gqlFetcher(mutation, {
input,
})
const output = data as Response | undefined
console.log('output: ', output, output?.optInFeature?.errorCodes)
if (
output?.optInFeature?.errorCodes &&
output.optInFeature?.errorCodes?.indexOf(
OptInFeatureErrorCode.Ineligible
) !== -1
) {
return {
ineligible: true,
}
}
2024-03-28 07:53:13 +00:00
if (
!output ||
!output.optInFeature.feature ||
!output.optInFeature.feature.grantedAt
) {
return {}
}
return {
feature: output.optInFeature.feature,
2024-03-19 02:12:49 +00:00
}
} catch (err) {
console.log('error opting into feature')
return {}
2024-03-19 02:12:49 +00:00
}
}