import { adminStore } from '../admin-store' import { fetcher as _fetcher, routes } from '@vtex/raccoon-core' import { MyVtexGraphQLOptions, MyVtexGraphQLParams } from './types' /** * Fetches data authenticated with the VTEX ID token. * * When using the `proxy` option, this method doesn't * use the underlying fetcher from `@vtex/raccoon-core`, * which goes through the `@vtex/raccoon-proxy` library. * * Instead, it uses the native `fetch` method and since * the application is already running under *.myvtex.com, * it will be authenticated by the VTEX ID token and it * doesn't need to go through the proxy. */ export async function fetcher( route: string | URL | Request, options: RequestInit = {}, ) { const { proxy } = adminStore.read() if (!proxy) { const { token, account, workspace } = adminStore.read() return _fetcher(route, { ...options, token, account, workspace, }) } return fetch(route, { ...options, headers: { ...options.headers, target: new URL(proxy.appUrl).host, }, }) } /** * Hits myvtex GraphQL endpoint with the given body */ export async function fetchMyVtexGraphQL(params: MyVtexGraphQLParams) { const { body, options } = params const { workspace } = adminStore.read() return fetcher(routes.myVtex.graphql({ ...options, workspace }), { method: 'POST', body, ...options, }) } /** * Factory function to create a query function for a given query body * * @example * const UserRoles = JSON.stringify({ * query: `query UserRoles {\n userRoles @context(provider: "vtex.admin-graphql@2.x") {\n roles {\n id\n isAdmin\n roleType\n name\n }\n }\n}`, * variables: null, * operationName: "UserRoles", * }); * * const fetchUserRoles = createGraphQLQuery(UserRoles) * const { locale } = useAdmin() * * fetchUserRoles({ * locale, * }) */ export function createGraphQLQuery(body: string) { return async function (options: MyVtexGraphQLOptions) { const params: MyVtexGraphQLParams = { body, options, } return fetchMyVtexGraphQL(params) } }