Silk
The silk is the basic material of the GraphQL Loom, and it reflects both GraphQL types and TypeScript types. At development time, we use the Schema of an existing schema library as the silk, and eventually GQLoom will weave the silk into the GraphQL Schema.
Simple scalar silk
We can create a simple scalar silk using the silk function:
import { silk } from "@gqloom/core"
import { GraphQLString, GraphQLInt, GraphQLNonNull } from "graphql"
const StringSilk = silk(GraphQLString)
const IntSilk = silk(GraphQLInt)
const NonNullStringSilk = silk(new GraphQLNonNull(GraphQLString))
const NonNullStringSilk1 = silk.nonNull(StringSilk)Object silk
We can construct GraphQL objects directly using graphql.js:
import { silk } from "@gqloom/core"
import {
GraphQLObjectType,
GraphQLNonNull,
GraphQLString,
GraphQLInt,
} from "graphql"
interface ICat {
name: string
age: number
}
const Cat = silk(
new GraphQLObjectType<ICat>({
name: "Cat",
fields: {
name: { type: new GraphQLNonNull(GraphQLString) },
age: { type: new GraphQLNonNull(GraphQLInt) },
},
})
)In the above code: we define an ICat interface and a silk named Cat using the silk function. The silk function accepts ICat as a generic parameter and also accepts a GraphQLObjectType instance to elaborate the structure of Cat in GraphQL.
Cat will be presented in GraphQL as:
type Cat {
name: String!
age: Int!
}You may have noticed that using graphql.js to create silk requires the declaration of both the ICat interface and the GraphQLObjectType, which means that we have created two definitions for Cat. Duplicate definitions cost the code simplicity and increased maintenance costs.
Creating silk using Schema libraries
Fortunately, we have Schema libraries like Valibot and Zod that create Schemas that carry TypeScript types and still carry types at runtime. GQLoom can directly use these Schemas as silk without duplicate definitions.
GQLoom currently integrates Schemas from the following libraries:
Additionally, there are some libraries that can be used as silk through JSON Schema, such as TypeBox, ArkType, Effect Schema, etc.
import * as v from "valibot"
const StringSilk = v.string()
const BooleanSilk = v.boolean()
const Cat = v.object({
__typename: v.literal("Cat"),
name: v.string(),
age: v.number(),
})We can directly use Valibot Schema as silk, but don't forget to add ValibotWeaver from @gqloom/valibot when weaving.
import { weave } from "@gqloom/core"
import { ValibotWeaver } from "@gqloom/valibot"
export const schema = weave(ValibotWeaver, ...resolvers)