import fetch from 'isomorphic-fetch' ; import { GraphQLError } from 'graphql' ; import { Locale } from '@island.is/shared/types' ; import { User } from '@island.is/auth-nest-tools' ; import { Application } from './Application' ; import { FailedDataProviderResult , SuccessfulDataProviderResult , } from './DataProviderResult' ; import { coreErrorMessages } from '../lib/messages' ; export type CustomTemplateFindQuery = ( where : { [ key ] : string ; } ) => Promise < Application [ ] > ; export interface DataProvider { readonly type : string ; provide ( application , customTemplateFindQuery ) : Promise < unknown > ; onProvideError ( _ ) : FailedDataProviderResult ; onProvideSuccess ( _ ) : SuccessfulDataProviderResult ; } export interface DataProviderConfig { user : User | undefined ; baseApiUrl : string ; locale : Locale ; } export interface GraphqlGatewayResponse < DataType > extends Response { json : ( ) => Promise < { data ? : DataType ; errors ? : GraphQLError [ ] ; } > ; } export abstract class BasicDataProvider implements DataProvider { readonly type ! : string ; readonly config : DataProviderConfig ; constructor ( config = { user : undefined , baseApiUrl : '' , locale : 'is' as Locale , } ) { this . config = config ; } param application abstract provide ( application , customTemplateFindQuery ) ; protected async useGraphqlGateway < DataType = any > ( query , variables ? ) { return fetch ( `${ this . config . baseApiUrl }/api/graphql` , { method : 'POST' , headers : { 'Content-Type' : 'application/json' , Accept : 'application/json' , authorization : this . config . user ?. authorization ?? '' , } , body : JSON . stringify ( { query , variables , } ) , } ) ; } onProvideError ( _ ) { return { date : new Date ( ) , reason : coreErrorMessages . errorDataProvider , status : 'failure' , } ; } onProvideSuccess ( _ ) { return { data : true , date : new Date ( ) , status : 'success' , } ; } }