Record your life!
Dashboard
My Blogs
← Back to List
Create Blog
Title
Type
Diary
Blog
Category
Node.js
Content
Edit
Preview
- interface可以implements interface,但是最终会被type所继承,一个完整的例子。其中fragment可以共享字段 ``` interface Node{ id: Int! } interface Animal implements Node{ id: Int! age: Int! } type Human extends Animal{ id: Int! age: Int! name: String! } type Dog extends Animal{ id: Int! age: Int! type: String! } query CompareChinaAndKorea { china: getAnimals(country: "China"){ # 走fragment, ...animalFields ...humanFields # 这个是inlineFragment ... on Dog { type } }, korea: getAnimals(country: "Korea"){ # 走fragment, ...animalFields ...humanFields ... on Dog { type } } } # 共享字段 fragment animalFields on Animal { __typename id age } fragment humanFields on Human { name } ``` - union只能是多个Object类型(即type)的结合,不能是interface或者其他union类型 - input类型用于mutation和query类型的输入,但不能用输出。他跟type很像,为什么mutation和query的输入不能用它?因为type类型可以定义动态获取数据的resolver,input只是静态类型 - SDL的comment以#开头,不会透露道iql的客户端,但是description用“”“ ”“”包围,可以多行+支持markdown,使用者可以在代码提示处看到 - 一个query里可以查询多个,可以用alias做区别 ``` query { empireHero: hero(episode: EMPIRE) { name } jediHero: hero(episode: JEDI) { name } } ``` -只有当请求类型时query的时候,才可以用简写,mutation和subscription不可以省略关键字,比如 ``` { user(id: "1000"){ name } } # 等同于 query FindUser{ user(id: "1000"){ name } } # 但mutation和subscription不可以简写 ``` - graphql支持一个query里查询多个,也支持一个mutation里修改多个,但是query是并行的,mutation是串行的,且无法支持事物 ``` mutation DeleteShips { firstShip: deleteStarship(id: "3001") secondShip: deleteStarship(id: "3002") } ``` - 怎么根据gql生成类型,并且怎么使用 ``` // codgen.ts文件,npx graphql-codegen import type { CodegenConfig } from "@graphql-codegen/cli"; const config: CodegenConfig = { schema: "./src/schema.gql", generates: { "./src/types.ts": { plugins: ["typescript", "typescript-resolvers"], config: { // context对象要通过这种方式去声明类型,./context是相对于./src/types.ts的路径 // #DataSourceContext代表的是./context.ts中的DataSourceContext类型 contextType: "./context#DataSourceContext", } }, }, }; export default config; // context.ts定义上下文类型 import { ListingAPI } from "./datasources/listing-api"; export type DataSourceContext = { dataSources: { listingAPI: ListingAPI; }; }; // 最后在Resolver里使用 import { Resolvers } from "./types"; // resolver里每一个函数都可以拿到正确的parent, args, context等信息 export const resolvers: Resolvers = { Query:... Mutation:... } ```
Update