monaco-graphql 如何为 JSON 变量编辑器启用 schema 驱动的校验(validateVariablesJson)? monaco-graphql 如何为 JSON 变量编辑器启用 schema 驱动的校验validateVariablesJson【免费下载链接】graphiqlGraphiQL the GraphQL LSP Reference Ecosystem for building browser IDE tools.项目地址: https://gitcode.com/GitHub_Trending/gr/graphiql用monaco-graphql自建类 VS Code 的 GraphQL Web IDE 时通常会有两个编辑器一个编辑 GraphQL 操作.graphqlmodel另一个编辑以 JSON 形式提交的 variables。想让 variables 编辑器里的值按照操作声明的变量类型做 schema 驱动校验缺必填变量、类型不符时出诊断并能获得补全入口是MonacoGraphQLAPI的setDiagnosticSettings()方法其中的键就是标题里的validateVariablesJson——源码类型定义中的实际拼写是validateVariablesJSON。开始之前需要明确两点适用前提均来自仓库文档monaco-graphql处于 pre-release 状态README 明确提示 codemirror-graphql 拥有更多功能包括 JSON variables validation且更稳定见 packages/monaco-graphql/README.md变量校验依赖 monaco 的json语言模式内置 JSON Schema 支持且操作 model 必须能匹配到某个 schema 配置JSON Schema 才会被计算出来。先确认字段名README 与源码拼写不一致仓库中两处文档对该字段使用了不同拼写packages/monaco-graphql/README.md 的 Full Sync Demo with Variables JSON 与getDiagnosticOptions两节写的是validateVariablesJson实际的类型定义 packages/monaco-graphql/src/typings/index.ts 中DiagnosticSettings的字段是validateVariablesJSONwebpack 示例 examples/monaco-graphql-webpack/src/index.ts 使用的也是validateVariablesJSON。运行时读取的正是源码里的validateVariablesJSON见 packages/monaco-graphql/src/languageFeatures.ts 中defaults.diagnosticSettings.validateVariablesJSON?.[modelUri]所以代码里请以validateVariablesJSON为准。准备条件安装、model 与 schema 注册安装依赖README 给出的安装命令yarn add monaco-graphql创建两个 model。操作 model 使用graphql语言variables model 使用json语言各自有独立的 uri取自 webpack 示例 examples/monaco-graphql-webpack/src/editors.ts 的做法const operationModel editor.createModel( query {}, graphql, Uri.file(/1/operation.graphql), ); const variablesModel editor.createModel( {}, json, Uri.file(/1/variables.json), );注册 worker。monaco-graphql的 language worker 需要挂到MonacoEnvironment.getWorker上graphqllabel 返回 GraphQLWorkerREADME Sync Exampleimport * as monaco from monaco-editor/esm/vs/editor/editor.api; import { initializeMode } from monaco-graphql/initializeMode; // README 中 webpack 场景使用 worker-loader!monaco-graphql/esm/graphql.worker // README 同时提示 monaco-graphql/esm/* 模式已弃用规范子路径为 monaco-graphql/graphql.worker import GraphQLWorker from worker-loader!monaco-graphql/esm/graphql.worker; globalThis.MonacoEnvironment { getWorker(_workerId: string, label: string) { if (label graphql) { return new GraphQLWorker(); } return new Worker(editor.worker.js); }, };用initializeMode注册 schema且fileMatch必须能匹配到操作 model 的 uri。匹配逻辑由SchemaConfig.fileMatch提供支持具体 uri 和picomatch表达式README Features 与类型定义 packages/monaco-graphql/src/typings/index.ts 均如此说明const MonacoGraphQLAPI initializeMode({ schemas: [ { // anything that monaco.URI.from() is compatible with uri: https://my-schema.com, // match the monaco file uris for this schema. fileMatch: [**/*.graphql], schema: myGraphqlSchema as GraphQLSchema, }, ], });这里的myGraphqlSchema是你自己接入的GraphQLSchema实例属于读者必须提供的值。启用变量 JSON 校验setDiagnosticSettings在两个 model 都创建好之后调用setDiagnosticSettings把操作 model 的 uri映射到variables model 的 uri 列表README Full Sync Demo with Variables JSON 的高层配置方法MonacoGraphQLAPI.setDiagnosticSettings({ validateVariablesJSON: { // Urls, uris, anything that monaco.URI.from() is compatible with. // Match operation model to variables editor, // and the language service will automatically listen for changes, // and compute the json schema using the GraphQLWorker. // This is in the main process is applied to the global monaco json settings // for validation, completion and more using monaco-jsons built-in JSON Schema support. [operationModel.uri.toString()]: [variablesModel.uri.toString()], }, jsonDiagnosticSettings: { allowComments: true, // allow json, parse with a jsonc parser to make requests }, });各配置的作用依据 README 与类型定义注释validateVariablesJSON值为Recordstring, string[]键是操作 model 的 uri 字符串值是 variables model 的 uri 字符串数组。配置后语言服务会自动监听变更并用 GraphQLWorker 计算 JSON SchemaREADME 原文说明。jsonDiagnosticSettings透传给 monacojson模式的JSONDiagnosticOptions。类型定义中给出的可用项示例包括allowComments: true启用 jsonc 编辑、schemaValidation: warning、trailingCommas。不配置时api.ts中的默认值是{ schemaValidation: error }packages/monaco-graphql/src/api.ts 的diagnosticSettingDefault且实际写入 json 设置时固定带上schemaValidation: error、validate: true。setDiagnosticSettings是运行时 API随时调用都会触发 webworker 重新加载相关 language featuresREADME MonacoGraphQLAPI 一节如果你同步import monaco-graphql也可以通过monaco.languages.graphql.api拿到同一个 API。校验如何生效worker 计算 schema写入 monaco json 全局设置理解生效机制有助于判断为什么我的 variables 没有报错/补全。源码路径是 packages/monaco-graphql/src/languageFeatures.tsDiagnosticsAdapter只监听语言 id 为graphql的 model即你的操作 model并在内容变更后以 400ms 防抖触发校验若该操作 model 的 uri 在validateVariablesJSON中有登记则动态 import monaco 的 json 模式monaco-editor/esm/vs/language/json/monaco.contribution.js再调用 worker 的doGetVariablesJSONSchemaworker 侧由LanguageService.getVariablesJSONSchema基于该文件的 schema 与操作文档计算variableToType并生成 JSON Schemapackages/monaco-graphql/src/LanguageService.tsworker 会给结果加上$id: monaco://variables-schema.json和title: GraphQL Variablespackages/monaco-graphql/src/GraphQLWorker.ts主进程把该 schema 以fileMatch指向 variables model 的 uri 写入languages.json.jsonDefaults的诊断选项此后 variables 编辑器的校验、补全等由 monaco-json 的内置 JSON Schema 支持完成README 原文applied to the global monaco json settings for validation, completion and more using monaco-jsons built-in JSON Schema support。由此可以读出两个前置条件schema 配置必须能匹配操作 model 的 uri否则getSchemaForFile拿不到 schema直接返回null操作文档内容需可解析且非空源码中要求documentText.length 3。验证运行示例工程观察变量编辑器仓库自带一个minimal example with variables (C)JSON support的 vite react 示例以及一个功能更全的 webpack 示例。monorepo 的启动方式见 examples/monaco-graphql-react-vite/README.md# 在 monorepo 根目录 pnpm install pnpm build # 在对应示例目录 pnpm dev以 webpack 示例为例examples/monaco-graphql-webpack/src/index.ts它完整演示了上述配置monacoGraphQLAPI.setDiagnosticSettings({ validateVariablesJSON: { [operationUri]: [variablesModel.uri.toString()], }, jsonDiagnosticSettings: { // jsonc tip! allowComments: true, schemaValidation: error, // this is nice too trailingCommas: warning, }, });该示例预置的 variables 内容examples/monaco-graphql-webpack/src/editors.ts文档示例与示例查询query Example($owner: String! $name: String! $reviewEvent: PullRequestReviewEvent! $user: FollowUserInput!)明显不一致——缺少$owner/$username给的是 Boolean{ reviewEvent: graphql, name: true }启动示例后在 variables 编辑器中编辑这段内容即可按 README 所述观察 monaco-json 基于计算出的 JSON Schema 给出的 validation 与 completion 行为操作文档中变量声明变化时schema 会随操作 model 的变更被重新计算。边界与注意包版本getVariablesJSONSchema方法自monaco-graphql0.5.0引入README Variables JSON Support!README TODO 中 variables JSON validation 与 variables completion 均已完成。lite 导入从monaco-graphql/lite导入时默认只有 highlighting 和 validationcompletion 等需要手动 import 对应 monaco contrib 后才会生效README monaco-graphql/lite 一节的 Warning。json 模式打包variables 校验依赖 monaco 的 json 语言模式。README Avoid Bundle All monaco-editors Languages 一节说明monaco-graphql1.3.0及以上可用monaco-graphql/monaco-editor替换全部monaco-editor导入只加载graphql与json两种语言。弃用子路径monaco-graphql/esm/*导入模式已弃用保留以兼容新代码应使用规范子路径monaco-graphql/monaco-editor、monaco-graphql/initializeMode、monaco-graphql/graphql.worker、monaco-graphql/lite。成熟度如开头所述monaco-graphql是 pre-release如果 JSON 变量校验是核心诉求且要求稳定README 建议的替代是codemirror-graphql。【免费下载链接】graphiqlGraphiQL the GraphQL LSP Reference Ecosystem for building browser IDE tools.项目地址: https://gitcode.com/GitHub_Trending/gr/graphiql创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考