@getanthill/datastore
Version:
Event-Sourced Datastore
106 lines (87 loc) • 2.41 kB
text/typescript
import type { AxiosResponse } from 'axios';
import type Core from './Core';
import { EventEmitter } from 'events';
import merge from 'lodash/merge';
import { Any, AnyObject, Telemetry } from '../typings';
export interface GraphQLConfig {
telemetry?: Telemetry;
}
export default class GraphQL extends EventEmitter {
static ERRORS = {};
private _config: GraphQLConfig = {};
public core: Core;
constructor(config: GraphQLConfig, core: Core) {
super();
this._config = merge({}, this._config, config);
this.core = core;
}
/**
* GraphQL API
* @alpha
*
* @see https://graphql.org/learn/serving-over-http/#post-request
*
* @param query
* @param variables
* @param operationName
*/
async request(
type: string,
query: string,
variables: { [key: string]: string[] } = {},
operationName = 'Op',
): Promise<AxiosResponse> {
const apiKey = `${type === 'query' ? 'viewer' : 'mutationViewer'}ApiKey`;
const operationVariables = [];
const _variables: { [key: string]: string } = {};
for (const variable in variables) {
operationVariables.push(`$${variable}: ${variables[variable][0]}`);
_variables[variable] = variables[variable][1];
}
const res = await this.core.request({
method: 'post',
url: this.core.getPath('graphql'),
data: {
query: `
${type} ${operationName}($token: String!${
operationVariables.length ? ', ' + operationVariables.join(', ') : ''
}) {
${apiKey}(apiKey: $token) {
${query}
}
}`,
operationName,
variables: {
..._variables,
token: this.core.getToken(),
},
},
});
const response: {
errors?: AnyObject[];
data?: Any;
} = {};
if (res.data.errors) {
response.errors = res.data.errors;
}
if (res.data?.data?.[apiKey]) {
response.data = res.data.data[apiKey];
}
res.data = response;
return res;
}
async query(
query: string,
variables?: { [key: string]: string[] },
operationName?: string,
): Promise<AxiosResponse> {
return this.request('query', query, variables, operationName);
}
async mutation(
query: string,
variables?: { [key: string]: string[] },
operationName?: string,
): Promise<AxiosResponse> {
return this.request('mutation', query, variables, operationName);
}
}