PostGraphile Schema-Only UsagePostGraphile 纯 Schema 用法
The PostGraphile library mode gives you a lot of excellent features for running your own GraphQL server. However, if you want to execute a PostGraphile query in Node.js without having to go through HTTP you can use some other exported functions that PostGraphile provides.
PostGraphile 库模式为自建 GraphQL 服务器提供了许多出色特性。但如果你想在 Node.js 中直接执行 PostGraphile 查询,而不经过 HTTP 层,也可以使用 PostGraphile 导出的另外几个底层函数。
If you're looking for Apollo Client SSR support for PostGraphile without a network roundtrip, check out GraphileApolloLink in Graphile Starter.
如果你希望在 Apollo Client SSR 中使用 PostGraphile 且避免网络往返开销,可以参考 Graphile Starter 中的 GraphileApolloLink。
Getting the schema获取 schema
First you will need a PostGraphile instance, typically called pgl. If you're
already using PostGraphile somewhere, you can likely import it from there;
but if not you can create it yourself:
首先,你需要一个 PostGraphile 实例(通常命名为 pgl)。如果项目中其他地方已经创建过它,直接导入即可;否则可以按如下方式自行创建:
import { postgraphile } from "postgraphile";
import preset from "./graphile.config.js";
export const pgl = postgraphile(preset);
You can then get the schema result from this instance; this is an object consisting of:
接着就可以从该实例获取 schema 结果,它是一个包含以下属性的对象:
-
schema- the GraphQL schemaschema—— 生成的 GraphQL schema -
resolvedPreset- the resolved presetresolvedPreset—— 解析后的最终 preset
import { pgl } from "./pgl.js";
const { schema, resolvedPreset } = await pgl.getSchemaResult();
You should call the above function whenever you need the schema, rather than caching the result — the reason is that in "watch" mode the schema (and preset) may change over time, so this is a safe way to get the latest schema.
每次需要用到 schema 时都应调用上述方法,而不要自行缓存其返回结果——因为在“watch”模式下,schema(以及 preset)可能会随数据库变更而更新,每次调用才能安全地拿到最新版本。
If you want to get a schema with minimal overhead and are not concerned
about supporting "watch" mode, you can instead call makeSchema directly:
如果你希望以最小开销获取 schema 且无需支持“watch”模式,也可以直接调用 makeSchema:
import { makeSchema } from "postgraphile";
import preset from "./graphile.config.js";
const { schema, resolvedPreset } = await makeSchema(preset);
Easy execution: grafast()便捷执行:grafast()
Now that you have schema and resolvedPreset, you can execute a GraphQL
query via:
拿到了 schema 和 resolvedPreset 之后,就可以通过以下方式执行 GraphQL 查询:
import { grafast } from "postgraphile/grafast";
const { data, errors } = await grafast({
schema,
resolvedPreset,
requestContext: {
// This is the "request context" - it is **NOT** the GraphQL context
},
source: /* GraphQL */ `
query MyQuery {
__typename
}
`,
variableValues: {},
});
grafast() is equivalent to graphql() except it also accepts two additional
optional entries in the args object: the resolvedPreset and the request
context requestContext. If you pass these parameters then grafast will
take care of building the GraphQL context for you based on what is in your
preset.
grafast() 与 graphql() 用法基本一致,只是在 args 参数对象中额外支持两个可选字段:resolvedPreset 和请求上下文 requestContext。只要传入这两个参数,grafast 就会根据你的 preset 配置自动构建 GraphQL 上下文。
requestContext is not the same as GraphQL's contextrequestContext 不同于 GraphQL 的 contextDo not confuse requestContext with the GraphQL context; requestContext is
the parameter passed to your preset.grafast.context(requestContext) callback
(and any plugins that need it) containing details of where the request came
from. In a node HTTP web server it would typically be something like
requestContext = { node: { req, res } } and would be used to extract things
like the Authorization header to determine who is making the request.
Different servers and situations may add alternative or additional information.
切勿将 requestContext 与 GraphQL 上下文(context)混淆。requestContext 是传给 preset.grafast.context(requestContext) 回调函数(以及任何依赖它的插件)的参数,其中包含请求来源的详细信息。在 Node HTTP 服务器中,它通常形如 requestContext = { node: { req, res } },用于提取 Authorization 请求头等信息以识别请求发起者;不同服务器或运行场景也可能会在其中附加其他字段。
Full example完整示例
Here's a full example:
下面是一个完整示例:
import { postgraphile } from "postgraphile";
import { grafast, type ErrorBehavior } from "postgraphile/grafast";
import preset from "./graphile.config.js";
// Make a new PostGraphile instance:
const pgl = postgraphile(preset);
// Or import a shared instance:
// import { pgl } from "./pgl.js"
/**
* Given a request context `requestContext`, GraphQL query text `source` and
* optionally variable values and operation name, execute the given GraphQL
* operation against our schema and return the result.
*/
export async function executeQuery(
requestContext: Partial<Grafast.RequestContext>,
source: string,
variableValues?: Record<string, unknown> | null,
operationName?: string,
onError?: ErrorBehavior,
) {
const { schema, resolvedPreset } = await pgl.getSchemaResult();
return await grafast({
schema,
source,
variableValues,
operationName,
onError,
resolvedPreset,
requestContext,
});
}
Execution with hookArgs()使用 hookArgs() 执行查询
If you do not (or can not) pass the requestContext and resolvedPreset
parameters to grafast(), or you want to deal with raw GraphQL documents
rather than source strings, then you will need to call hookArgs() yourself to
build the GraphQL context that PostGraphile will need in order to communicate
with the database. This also means that you're taking care of parsing and
validating the GraphQL request yourself.
如果你没有(或无法)向 grafast() 传入 requestContext 和 resolvedPreset,或者想直接处理已解析的原始 GraphQL 文档对象而非查询源码字符串,就需要自己调用 hookArgs() 来构建 PostGraphile 与数据库通信所需的 GraphQL 上下文。这也意味着你需要自行负责 GraphQL 请求的解析与校验。
If you're doing this inside a server framework, they will often give you a way
to hook the args before they're dispatched to execute — that is where you would
call hookArgs().
如果你是在某个服务器框架中集成,框架通常会在参数分发给执行器之前提供 hook 入口——这正是调用 hookArgs() 的位置。
Basic hookArgs example基础 hookArgs 示例
Here's an example using hookArgs:
下面是一个使用 hookArgs 的示例:
import { postgraphile } from "postgraphile";
import { parse, validate } from "postgraphile/graphql";
import { execute, hookArgs, type ErrorBehavior } from "postgraphile/grafast";
import preset from "./graphile.config.js";
// Build a `pgl` instance, with helpers and schema based on our preset.
const pgl = postgraphile(preset);
/**
* Given a request context `requestContext`, GraphQL query text `source` and
* optionally variable values and operation name, execute the given GraphQL
* operation against our schema and return the result.
*/
export async function executeQuery(
requestContext: Partial<Grafast.RequestContext>,
source: string,
variableValues?: Record<string, unknown> | null,
operationName?: string,
onError?: ErrorBehavior,
) {
// We might get a newer schema in "watch" mode
const { schema, resolvedPreset } = await pgl.getSchemaResult();
// Parse the GraphQL query text:
const document = parse(source);
// Validate the GraphQL document against the schema:
const errors = validate(schema, document);
if (errors.length > 0) {
return { errors };
}
// Prepare the execution arguments:
const args = await hookArgs({
schema,
document,
variableValues,
operationName,
onError,
resolvedPreset,
requestContext,
});
// Execute the request using Grafast:
return await execute(args);
}
Example using TypedDocumentNode使用 TypedDocumentNode 的示例
You can use GraphQL Code Generator with the client-preset to make your GraphQL
execution function type-safe. In this case, rather than passing in a raw
source string, we pass in a TypedDocumentNode which is generated by the
gql tagged template literal, and this means the result we return will
automatically reflect the correct types thanks to graphql-codegen:
你可以配合 GraphQL Code Generator 的 client-preset,让 GraphQL 执行函数具备完整的类型安全。此时不再传入原始 source 字符串,而是传入由 gql 标签模板字面量生成的 TypedDocumentNode,这样借助 graphql-codegen,返回结果就会自动携带精确的类型推导:
import type { DocumentNode, ExecutionResult } from "postgraphile/graphql";
import type {
TypedDocumentNode,
VariablesOf,
ResultOf,
} from "@graphql-typed-document-node/core";
import { postgraphile } from "postgraphile";
import { execute, hookArgs, type ErrorBehavior } from "postgraphile/grafast";
import { validate } from "postgraphile/graphql";
import preset from "./graphile.config.js";
const pgl = postgraphile(preset);
export async function executeDocument<
TDoc extends TypedDocumentNode | DocumentNode,
TExtensions = ObjMap<unknown>,
>(
requestContext: Partial<Grafast.RequestContext>,
document: TDoc,
variableValues?: VariablesOf<TDoc>,
operationName?: string,
onError?: ErrorBehavior,
): Promise<ExecutionResult<ResultOf<TDoc>, TExtensions>> {
const { schema, resolvedPreset } = await pgl.getSchemaResult();
// Validate the GraphQL document against the schema:
const errors = validate(schema, document);
if (errors.length > 0) {
return { errors };
}
// Prepare the execution arguments:
const args = await hookArgs({
schema,
document,
variableValues,
operationName,
onError,
resolvedPreset,
requestContext,
} as any);
// Execute the request using Grafast:
const result = await execute(args);
// Cast the result to the types implied by the TypedDocumentNode:
return result as ExecutionResult<ResultOf<TDoc>, TExtensions>;
}
Usage for gql.tada is
similar; just import the helpers from gql.tada instead and note that
TypedDocumentNode is renamed to TadaDocumentNode:
gql.tada 的用法也类似;只需改为从 gql.tada 导入相应的辅助类型,并注意 TypedDocumentNode 在其中重命名为了 TadaDocumentNode:
import type {
VariablesOf,
ResultOf,
- TypedDocumentNode,
+ TadaDocumentNode,
-} from "@graphql-typed-document-node/core";
+} from "gql.tada";