Skip to content

Instantly share code, notes, and snippets.

@jamesallain
Last active March 23, 2023 14:00
Show Gist options
  • Save jamesallain/ca09979840c4530f72ce16378e49b927 to your computer and use it in GitHub Desktop.
Save jamesallain/ca09979840c4530f72ce16378e49b927 to your computer and use it in GitHub Desktop.
import { withPgClient, withPgClientTransaction } from "@dataplan/pg";
import { context, each, lambda, object } from "grafast";
import { gql, makeExtendSchemaPlugin } from "graphile-utils";
/**
* TodoPlugin
*/
export const TodoPlugin = makeExtendSchemaPlugin((build) => {
const { sql, input } = build;
const executor = input.pgSources[0].executor;
const todos = build.input.pgSources.find(
(s) => s.extensions?.pg && s.extensions.pg.name === "todos"
);
if (!todos) {
throw new Error("Couldn't find todos source");
}
if (!sql) {
throw new Error("SQL is not available");
}
return {
typeDefs: gql`
input TodosInput {
userId: String!
}
type TodosPayload {
todos: [Todo!]!
}
extend type Mutation {
fetchTodos(input: TodosInput!): TodosPayload
}
`,
plans: {
Mutation: {
fetchTodos(_$root, fieldArgs) {
const $rootPgPool = context().get("rootPgPool");
const $input = object({
userId: fieldArgs.get(["input", "userId"]),
});
/**
* Fetch and insert data
*/
withPgClient(
executor,
object({
input: $input,
rootPgPool: $rootPgPool,
}),
async (_client, data) => {
const { userId } = data?.input;
const todos = await getTodosAPI({
input: { userId: userId },
});
if (!todos) throw new Error("Couldn't find Todos");
//Insert todos into postgres
}
);
/**
* Handle transactions
*/
const $transactionResult = withPgClientTransaction(
executor,
object({
input: $input,
rootPgPool: $rootPgPool,
}),
async (client, data) => {
const { userId } = data?.input;
const { rows } = await client.query(
sql.compile(
sql`SELECT *
FROM app_public.todos
WHERE user_id=${sql.value(userId)}`
)
);
return rows;
}
);
return $transactionResult;
},
},
TodosPayload: {
todos($transactionResult) {
const $ids = lambda($transactionResult, (records) =>
records.map((record) => record.id)
);
return each($ids, ($id) => todos.get({ id: $id }));
},
},
},
};
});
export default TodoPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment