generated from kimyvgy/worker-apollo-server-template
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Como crear una query en graphQL
Francisco Cordero edited this page Aug 6, 2023
·
1 revision
Se necesita crear una query que hace referencia al schema Foo que posee 3 atributos, los cuales son id, isActive y role. Para poder filtrar por foos activos e inactivos.
// /src/datasources/db/tables.ts
export const fooSchema = sqliteTable("foo", {
id: text("id").primaryKey().notNull(),
isActive: int("isActive", { mode: "boolean" }).default(true),
role: text("role", { enum: ["dev", "reviewer"] })
.default("dev")
.notNull(),
...createdAndUpdatedAtFields,
});
// /src/datasource/db/CRUD.ts
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import { fooSchema } from "~/datasources/db/tables";
export const selectFooSchema = createSelectSchema(fooSchema);
export const insertFooSchema = createInsertSchema(fooSchema);
// /src/schema/shared/refs.ts
import { z } from "zod";
import { builder } from "~/builder";
import { selectFooSchema } from "~/datasources/db/schema";
type FooGraphqlSchema = z.infer<typeof selectFooSchema>;
export const FooRef = builder.objectRef<FooGraphqlSchema>("Foo");
// /src/schema/foo.ts
import {
selectFooSchema,
} from "~/datasources/db/schema";
const FooRole = builder.enumType("FooRole", {
values: ["dev", "reviewer"]
});
builder.objectType(FooRef, {
description: "Representation of a foo",
fields: (t) => ({
id: t.exposeString("id", { nullable: false }),
isActive: t.exposeBoolean("isActive", { nullable: false }),
role: t.field({
type: FooRole,
nullable: false,
resolve: (root) => root.role,
}),
});
});
// /src/schema/foo.ts
const FooSearchInput = builder.inputType("FooSearchInput", {
fields: (t) => ({
isActive: t.field({
type: "Boolean",
required: false,
}),
}),
});
// /src/schema/foo.ts
builder.queryFields((t) => ({
foos: t.field({
type: [FooRef],
args: {
input: t.arg({ type: FooSearchInput, required: false }),
},
resolve: async (root, { input }, ctx) => {
const { isActive } = input ?? {};
const wheres: SQL[] = [];
if (isActive) {
wheres.push((foo) => foo.isActive === isActive);
}
const foos = await ctx.DB.query.fooSchema.findMany({
where: (foo) => foo.and(...wheres),
});
return foos.map((foo) => selectFooSchema.parse(foo));
},
});
}));
Dentro del resolve vamos agregando querys al array de wheres, donde se filtran por atributos enviados en la query, para luego retornar los foos filtrados por el where
Si tienes alguna pregunta/consulta puedes hacerlas en nuestro canal de #「💻☕」hackathon
en nuestro servidor de discord
Made with ❤️ from Javascript Chile