@getanthill/datastore
Version:
Event-Sourced Datastore
69 lines • 2.3 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const events_1 = require("events");
const merge_1 = __importDefault(require("lodash/merge"));
class GraphQL extends events_1.EventEmitter {
constructor(config, core) {
super();
this._config = {};
this._config = (0, merge_1.default)({}, 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, query, variables = {}, operationName = 'Op') {
const apiKey = `${type === 'query' ? 'viewer' : 'mutationViewer'}ApiKey`;
const operationVariables = [];
const _variables = {};
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 = {};
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, variables, operationName) {
return this.request('query', query, variables, operationName);
}
async mutation(query, variables, operationName) {
return this.request('mutation', query, variables, operationName);
}
}
GraphQL.ERRORS = {};
exports.default = GraphQL;
//# sourceMappingURL=GraphQL.js.map