iT邦幫忙

2023 iThome 鐵人賽

DAY 20
0
Modern Web

由前向後,從前端邁向全端系列 第 20

20.【從前端到全端,Nextjs+Nestjs】在Nx中設置NestJS GraphQL server

  • 分享至 

  • xImage
  •  

文章重點

  • 安裝必要的依賴包以設置GraphQL環境。
  • 創建配置文件以定義GraphQL和其他相關設置。
  • 建立GraphQL模組和配置服務來初始化GraphQL伺服器。

本文

1.安裝依賴

執行以下命令來安裝必要的NestJS和GraphQL依賴包:
pnpm add @nestjs/config @nestjs/graphql @nestjs/apollo @apollo/server

2.創建graphql module

首先,我們需要建立一個配置文件來保存我們的項目設置,如GraphQL和Nest一些的基本設置。

建立config配置文件並設置:

///// apps\iron-ecommerce-server\src\common\configs\config.interface.ts

export interface Config {
	nest: NestConfig;
	cors: CorsConfig;
	graphql: GraphqlConfig;
}

export interface NestConfig {
	port: number;
}

export interface CorsConfig {
	enabled: boolean;
}

export interface GraphqlConfig {
	codefirst: {
		playgroundEnabled: boolean;
		debug: boolean;
		schemaDestination: string;
		sortSchema: boolean;
	};
}


///// apps\iron-ecommerce-server\src\common\configs\config.ts

import type { Config } from "./config.interface";

const config: Config = {
	nest: {
		port: 3000
	},
	cors: {
		enabled: true
	},
	graphql: {
		codefirst: {
			playgroundEnabled: true,
			debug: true,
			schemaDestination: "apps/iron-ecommerce-server/src/graphql/schemas/schema.graphql",
			sortSchema: true
		}
	}
};

export default (): Config => config;



接著,我們創建一個service和一個module來配置GraphQL的運行環境

建立service和module

///// apps\iron-ecommerce-server\src\graphql\gql-config.service.ts

import { GraphqlConfig } from "../common/configs/config.interface";
import { ApolloDriverConfig } from "@nestjs/apollo";
import { Injectable } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { GqlOptionsFactory } from "@nestjs/graphql";

@Injectable()
export class GqlCodeFirstConfigService implements GqlOptionsFactory {
	constructor(private configService: ConfigService) {}
	createGqlOptions(): ApolloDriverConfig {
		const graphqlConfig = this.configService.get<GraphqlConfig>("graphql");
		return {
			// schema options
			autoSchemaFile: graphqlConfig.codefirst.schemaDestination,
			sortSchema: graphqlConfig.codefirst.sortSchema,
			buildSchemaOptions: {
				numberScalarMode: "integer"
			},
			// subscription
			installSubscriptionHandlers: true,
			includeStacktraceInErrorResponses: graphqlConfig.codefirst.debug,
			playground: graphqlConfig.codefirst.playgroundEnabled,
			context: ({ req }) => ({ req })
		};
	}
}


///// apps\iron-ecommerce-server\src\graphql\graphql-setup.module.ts

import { GqlCodeFirstConfigService } from "./gql-config.service";
import { ApolloDriver, ApolloDriverConfig } from "@nestjs/apollo";
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { GraphQLModule } from "@nestjs/graphql";

@Module({
	imports: [
		GraphQLModule.forRootAsync<ApolloDriverConfig>({
			driver: ApolloDriver,
			useClass: GqlCodeFirstConfigService
		}),
		ConfigModule
	],
	providers: [GqlCodeFirstConfigService],
	exports: [GraphQLModule]
})
export class GraphQLSetupModule {}


3.導入module

接下來我們引入ConfigModuleGraphQLSetupModule

///// apps\iron-ecommerce-server\src\app\app.module.ts

import config from "../common/configs/config";
import { GraphQLSetupModule } from "../graphql/graphql-setup.module";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";

@Module({
	imports: [ConfigModule.forRoot({ isGlobal: true, load: [config] }), GraphQLSetupModule],
	controllers: [AppController],
	providers: [AppService]
})
export class AppModule {}



4.創建Product GraphQL

現在,讓我們創建一個Product module和resolver來測試我們的GraphQL服務。

///// apps\iron-ecommerce-server\src\api\products\products.module.ts

import { ProductsResolver } from "./products.resolver";
import { Module } from "@nestjs/common";

@Module({
	imports: [],
	providers: [ProductsResolver]
})
export class ProductsModule {}


///// apps\iron-ecommerce-server\src\api\products\products.resolver.ts

import { Float, Query, Resolver } from "@nestjs/graphql";

@Resolver()
export class ProductsResolver {
	@Query(() => String)
	hello() {
		return "Hello World!";
	}
}

並將ProductsModule加入到我們AppModule裡:

///// apps\iron-ecommerce-server\src\app\app.module.ts
import { ProductsModule } from "../api/products/products.module";
import config from "../common/configs/config";
import { GraphQLSetupModule } from "../graphql/graphql-setup.module";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";

@Module({
	imports: [ConfigModule.forRoot({ isGlobal: true, load: [config] }), GraphQLSetupModule, ProductsModule],
	controllers: [AppController],
	providers: [AppService]
})
export class AppModule {}

5.執行

接下來我們測試一下,我們的Nextjs是否加入了GraphQL,輸入指令執行:

pnpm exec nx run iron-ecommerce-server:serve 

打開http://localhost:3000/graphql我們能看到啟動graphql playground,並且我們可以通過輸入查詢來測試我們的解析器,看看它是否正確地返回"Hello World!"
https://ithelp.ithome.com.tw/upload/images/20231005/201089318ampEb9Upo.png

並且我們能看到Nestjs產生了一個schema在apps\iron-ecommerce-server\src\graphql\schemas,這個方式就是codefirst。

///// apps\iron-ecommerce-server\src\graphql\schemas\schema.graphql

# ------------------------------------------------------
# THIS FILE WAS AUTOMATICALLY GENERATED (DO NOT MODIFY)
# ------------------------------------------------------

type Query {
  hello: String!
}

總結

本文介紹了如何在Nx工作空間中設置一個基本的NestJS GraphQL服務。從安裝必要的依賴開始,到建立配置、創建GraphQL模組、導入模組並運行測試。


上一篇
19.【從前端到全端,Nextjs+Nestjs】在 NX 中創建 Nest.js 後端
下一篇
21.【從前端到全端,Nextjs+Nestjs】利用GraphQL Schema First方法打造Nest.js的GraphQL服務
系列文
由前向後,從前端邁向全端30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言