如何基于GraphQL Schema生成的TypeScript类型动态定义GraphQL查询字符串
TypeScript动态构建GraphQL查询的实用库及示例
以下是几个适合在TypeScript中动态构建GraphQL查询的库,结合你已有的TS类型,可以实现类似Python gql DSL的功能:
1. graphql-js(官方工具)
官方GraphQL核心库提供了构建AST(抽象语法树)的API,可通过AST生成最终查询字符串,完全类型安全,能直接复用你的TS类型。
示例代码:
import { buildSchema, print } from 'graphql'; // 导入你已生成的GraphQL Schema(或直接使用生成的TS类型对应的Schema) const schema = buildSchema(` type Object { attribute: String attribute1: Int attribute2: String } type Query { Object(filter: FilterInput): Object } input FilterInput { attribute: ValueInput } input ValueInput { val: String } `); // 动态构建查询的函数 function buildDynamicQuery(objectName: string, filterField: string, filterValue: string, fields: string[]) { // 构建Filter参数AST节点 const filterArg = { kind: 'Argument', name: { kind: 'Name', value: 'filter' }, value: { kind: 'ObjectValue', fields: [{ kind: 'ObjectField', name: { kind: 'Name', value: filterField }, value: { kind: 'ObjectValue', fields: [{ kind: 'ObjectField', name: { kind: 'Name', value: 'val' }, value: { kind: 'StringValue', value: filterValue } }] } }] } }; // 构建字段选择集AST节点 const selectionSet = { kind: 'SelectionSet', selections: fields.map(field => ({ kind: 'Field', name: { kind: 'Name', value: field } })) }; // 构建完整查询AST const queryNode = { kind: 'Document', definitions: [{ kind: 'OperationDefinition', operation: 'query', selectionSet: { kind: 'SelectionSet', selections: [{ kind: 'Field', name: { kind: 'Name', value: objectName }, arguments: [filterArg], selectionSet }] } }] }; // 将AST转为字符串 return print(queryNode); } // 对应需求的使用示例 const query = buildDynamicQuery('Object', 'attribute', 'value', ['attribute', 'attribute1', 'attribute2']); console.log(query);
输出结果与你示例中的查询一致,且能通过TS类型约束参数合法性。
2. graphql-query-builder
这个库封装了更简洁的API,无需直接操作AST,风格贴近Python gql的DSL,上手成本低。
示例代码:
import { query, arg, objectArg } from 'graphql-query-builder'; function buildDynamicQuery(objectName: string, filterField: string, filterValue: string, fields: string[]) { const filter = objectArg({ [filterField]: objectArg({ val: filterValue }) }); return query({ [objectName]: [ arg({ filter }), fields ] }); } // 使用示例 const query = buildDynamicQuery('Object', 'attribute', 'value', ['attribute', 'attribute1', 'attribute2']); console.log(query);
3. gql-tag + 动态模板字符串
若你熟悉gql-tag(常见于Apollo生态),可结合动态模板字符串和TS类型构建查询,直观易读。
示例代码:
import gql from 'graphql-tag'; function buildDynamicQuery(objectName: string, filterField: string, filterValue: string, fields: string[]) { const fieldsStr = fields.join('\n '); const queryAST = gql` query { ${objectName}(filter: {${filterField}: {val: "${filterValue}"}}) { ${fieldsStr} } } `; return queryAST.loc.source.body; } // 使用示例 const query = buildDynamicQuery('Object', 'attribute', 'value', ['attribute', 'attribute1', 'attribute2']); console.log(query);
配合TS类型可约束objectName、filterField和fields必须符合生成的类型定义,避免拼写错误。
内容的提问来源于stack exchange,提问作者aman bhardwaj
相关产品推荐
相关产品推荐

