LoopBack 4是一款基于Node.js的开源框架,用于构建RESTful API和微服务应用程序。OpenAPI-to-GraphQL是一个用于将OpenAPI规范转换为GraphQL服务的工具。在LoopBack 4中使用OpenAPI-to-GraphQL启用GraphQL订阅的步骤如下:
@loopback/openapi-to-graphql
和@loopback/graphql
两个包:npm install @loopback/openapi-to-graphql @loopback/graphql
graphql.server.ts
的文件,并将以下代码复制到文件中:import {BootMixin} from '@loopback/boot';
import {ApplicationConfig} from '@loopback/core';
import {GraphQLBindings, GraphQLComponent} from '@loopback/graphql';
import {RepositoryMixin} from '@loopback/repository';
import {RestApplication, RestBindings, toInterceptor} from '@loopback/rest';
import {ServiceMixin} from '@loopback/service-proxy';
import {OpenApiToGraphQL} from '@loopback/openapi-to-graphql';
export class MyApp extends BootMixin(ServiceMixin(RepositoryMixin(RestApplication))) {
constructor(options: ApplicationConfig = {}) {
super(options);
// Set up GraphQL component
this.component(GraphQLComponent);
// Enable GraphQL subscriptions
this.configure(GraphQLBindings.GRAPHQL_SUBSCRIPTIONS).to(true);
}
async boot() {
await super.boot();
// Get the OpenAPI spec
const openApiSpec = await this.restServer.getApiSpec();
// Create a GraphQL schema from the OpenAPI spec
const openApiToGraphQL = new OpenApiToGraphQL({
openApiSpec,
});
const {schema, resolvers} = openApiToGraphQL.createSchema();
// Register GraphQL schema and resolvers
this.bind(GraphQLBindings.GRAPHQL_SCHEMA).to(schema);
this.bind(GraphQLBindings.GRAPHQL_RESOLVERS).to(resolvers);
}
}
src/index.ts
文件,并将以下代码添加到文件中:import {MyApp} from './graphql.server';
export async function main(options: ApplicationConfig = {}) {
const app = new MyApp(options);
await app.boot();
await app.start();
console.log(`Server is running at ${app.restServer.url}`);
console.log(`Try ${app.restServer.url}/graphql`);
return app;
}
// Start the application
main().catch(err => {
console.error('Cannot start the application.', err);
process.exit(1);
});
npm start
http://localhost:3000/graphql
来打开GraphQL Playground,该工具提供了与GraphQL API交互的界面。这是在LoopBack 4中使用OpenAPI-to-GraphQL启用GraphQL订阅的基本步骤。通过这种方式,你可以使用GraphQL来查询、变异和订阅你的LoopBack 4应用程序的数据。如果你想深入了解LoopBack 4的功能和其他相关内容,请参阅LoopBack 4文档。
领取专属 10元无门槛券
手把手带您无忧上云