Skip to content

Instantly share code, notes, and snippets.

@boopathi
Created February 18, 2020 22:39
Show Gist options
  • Save boopathi/364cc2a6156b0f69b644be687f1280ee to your computer and use it in GitHub Desktop.
Save boopathi/364cc2a6156b0f69b644be687f1280ee to your computer and use it in GitHub Desktop.
const resolvers = {
Query: {
async product(_, { id }, __, info) {
const fields = getFields(info);
const backendFields = getBackendFields(fields, dependencyMap);
const backendResponse = await fetch(`/product?id=${id}&fields=${backendFields}`);
const schemaResponse = getSchemaResponse(backendResponse, fields, transformerMap);
return schemaResponse;
}
}
};
const dependencyMap = {
name: ["title"],
price: ["price.currency", "price.amount"],
stock: ["stock_availability"],
};
const transformerMap = {
name: resp => resp.title,
price: resp => `${resp.currency} ${resp.amount}`,
stock: resp => resp.stock_availability,
};
function getFields(info) {
return info
.fieldNodes[0] // TODO: handle all field nodes in other fragments
.selectionSet
.selections
.map(
selection => // TODO: handle fragments
selection.name.value
);
}
function getBackendFields(schemaFields, dependencyMap) {
// Set helps in deduping
const backendFields = new Set(
schemaFields
.map(field => dependencyMap[field])
.reduce((acc, field) => [...acc, ...field], [])
);
return backendFields.join(",");
}
function getSchemaResponse(
backendResponse,
transformerMap,
schemaFields
) {
const schemaResponse = {};
for (const field of schemaFields) {
schemaResponse[field] = transformerMap[field](backendResponse);
}
return schemaResponse;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment