import { graphqlEndpoint , secret } from "./env" ; import getConfig from "./getConfig" ; import fetch from "node-fetch" ; import { status } from "./logger" ; const regionMap = new Map ( [ [ "eu" , "https://graphql.eu.fauna.com" ] , [ "us" , "https://graphql.us.fauna.com" ] , [ "classic" , "https://graphql.fauna.com" ] , [ "preview" , "https://graphql.fauna-preview.com" ] , [ "local" , "http://localhost:8084" ] ] ) ; let establishedEndpoint ; export default async function getGraphqlEndpoint ( _useSavedEndpoint = true ) { if ( establishedEndpoint && _useSavedEndpoint ) return establishedEndpoint ; if ( graphqlEndpoint ) return graphqlEndpoint ; const config = getConfig ( ) ; if ( config . region ) return regionMap . get ( config . region ) ; return findValidEndpoint ( ) ; } async function findValidEndpoint ( ) { const endpoints = [ ] ; regionMap . forEach ( ( value ) => { endpoints . push ( value ) ; } ) ; const results = await Promise . allSettled ( endpoints . map ( async ( endpoint ) => { return fetch ( `${ endpoint }/graphql` , { method : "POST" , headers : { "Authorization" : `Bearer ${ secret }` , "Content-Type" : "text/plain" } } ) ; } ) ) ; try { const index = await new Promise ( ( resolve , reject ) => { results . forEach ( async ( result , index ) => { if ( result . status !== "fulfilled" ) return ; const res = await result . value . json ( ) ; const message = res . errors [ 0 ] . message ; const regex = /^Invalid database secret/i ; const ok = ! regex . test ( message ) ; if ( ok ) resolve ( index ) ; if ( index === results . length - 1 ) reject ( "Could not find correct endpoint. Make sure your secret key is correct." ) ; } ) ; } ) ; const endpoint = endpoints [ index ] ; status ( `Your GraphQL region was inferred from your secret key and your endpoint was set to '${ endpoint }'. Use the 'region' option to set it explicitly.\nMore info: https://fgu-docs.com/configuration/config-file/\n` , "info" ) ; establishedEndpoint = endpoint ; return endpoint ; } catch { return null ; } }