首页 > 其他分享 >Get Started with Apollo Server

Get Started with Apollo Server

时间:2024-11-24 20:01:44浏览次数:9  
标签:Started Server server GraphQL our Apollo your

Get Started with Apollo Server


This tutorial helps you:

  • Obtain a basic understanding of GraphQL principles

  • Define a GraphQL schema that represents the structure of your data set

  • Run an instance of Apollo Server that lets you execute queries against your schema

This tutorial assumes that you are familiar with the command line and JavaScript and have installed a recent Node.js (v14.16.0+) version. Additionally, for those interested, this tutorial includes an optional section describing how to set up Apollo Server with TypeScript.

Step 1: Create a new project

  1. From your preferred development directory, create a directory for a new project and cd into it:

  Bash
1mkdir graphql-server-example
2cd graphql-server-example
  1. Initialize a new Node.js project with npm (or another package manager you prefer, such as Yarn):

  Bash
1  npm init --yes && npm pkg set type="module"

This getting started guide sets up a project using ES Modules, which simplifies our examples and allows us to use top-level await.

Your project directory now contains a package.json file.

Step 2: Install dependencies

Applications that run Apollo Server require two top-level dependencies:

  • graphql (also known as graphql-js) is the library that implements the core GraphQL parsing and execution algorithms.

  • @apollo/server is the main library for Apollo Server itself. Apollo Server knows how to turn HTTP requests and responses into GraphQL operations and run them in an extensible context with support for plugins and other features.

Run the following command to install both of these packages and save them in your project's node_modules directory:

  Bash
1  npm install @apollo/server graphql

Follow the instructions below to set up with either TypeScript or JavaScript:

  Set up with TypeScript (**Recommended**)     Set up with JavaScript  

Step 3: Define your GraphQL schema

ⓘ note The code blocks below use TypeScript. If your project uses JavaScript, you need to transpile the code.

Every GraphQL server (including Apollo Server) uses a schema to define the structure of data that clients can query. In this example, we'll create a server for querying a collection of books by title and author.

Open index.ts in your preferred code editor and paste the following into it:

  TypeScript index.ts
1import { ApolloServer } from '@apollo/server';
2import { startStandaloneServer } from '@apollo/server/standalone';
3
4// A schema is a collection of type definitions (hence "typeDefs")
5// that together define the "shape" of queries that are executed against
6// your data.
7const typeDefs = `#graphql
8  # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.
9
10  # This "Book" type defines the queryable fields for every book in our data source.
11  type Book {
12    title: String
13    author: String
14  }
15
16  # The "Query" type is special: it lists all of the available queries that
17  # clients can execute, along with the return type for each. In this
18  # case, the "books" query returns an array of zero or more Books (defined above).
19  type Query {
20    books: [Book]
21  }
22`;

Adding #graphql to the beginning of a template literal provides GraphQL syntax highlighting in supporting IDEs.

This snippet defines a simple, valid GraphQL schema. Clients will be able to execute a query named books, and our server will return an array of zero or more Books.

Step 4: Define your data set

Now that we've defined the structure of our data, we can define the data itself.

Apollo Server can fetch data from any source you connect to (including a database, a REST API, a static object storage service, or even another GraphQL server). For the purposes of this tutorial, we'll hardcode our example data.

Add the following to the bottom of your index.ts file:

  TypeScript index.ts
1const books = [
2  {
3    title: 'The Awakening',
4    author: 'Kate Chopin',
5  },
6  {
7    title: 'City of Glass',
8    author: 'Paul Auster',
9  },
10];

This snippet defines a simple data set that clients can query. Notice that the two objects in the array each match the structure of the Book type we defined in our schema.

Step 5: Define a resolver

We've defined our data set, but Apollo Server doesn't know that it should use that data set when it's executing a query. To fix this, we create a resolver.

Resolvers tell Apollo Server how to fetch the data associated with a particular type. Because our Book array is hardcoded, the corresponding resolver is straightforward.

Add the following to the bottom of your index.ts file:

  TypeScript index.ts
1// Resolvers define how to fetch the types defined in your schema.
2// This resolver retrieves books from the "books" array above.
3const resolvers = {
4  Query: {
5    books: () => books,
6  },
7};

Step 6: Create an instance of ApolloServer

We've defined our schema, data set, and resolver. Now we need to provide this information to Apollo Server when we initialize it.

Add the following to the bottom of your index.ts file:

  TypeScript index.ts
1// The ApolloServer constructor requires two parameters: your schema
2// definition and your set of resolvers.
3const server = new ApolloServer({
4  typeDefs,
5  resolvers,
6});
7
8// Passing an ApolloServer instance to the `startStandaloneServer` function:
9//  1. creates an Express app
10//  2. installs your ApolloServer instance as middleware
11//  3. prepares your app to handle incoming requests
12const { url } = await startStandaloneServer(server, {
13  listen: { port: 4000 },
14});
15
16console.log(`

标签:Started,Server,server,GraphQL,our,Apollo,your
From: https://www.cnblogs.com/sexintercourse/p/18566285

相关文章

  • 全新向量数据库SQL Server 2025:带你迈入AI驱动的数据未来
    全新向量数据库SQLServer2025:带你迈入AI驱动的数据未来 全新向量数据库SQLServer2025:带你迈入AI驱动的数据未来  上次大家下单的《微软憋大招:SQLServer+Copilot=地表最强AI数据库!》抱怨迟迟没有发货,这次微软没有食言,终于发货!前言随着人工智能技术的普及,客户......
  • UniversalMediaServer DLNA&Upnp & http 媒体服务
    UniversalMediaServer是一个强大的媒体服务,支持DLNA,Upnp,http协议说明UniversalMediaServer使用了ffmpeg,mediainfo,opensubtitles,crowdin,mencoder,tsmuxer,avisynth,vlc等开源技术,支持比较多的媒体格式,实际上DLNA协议在无线投屏领域使用的也比较多参考资料https://github.com/......
  • 计算机网络socket编程(5)_TCP网络编程实现echo_server
    个人主页:C++忠实粉丝欢迎点赞......
  • cornerstone中raft_server源码解析
    1.概述cornerstone中核心即为raft_server的实现。在raft里面有follower,leader,candidate三种角色,且角色身份还可以相互切换。写三个类follower,leader,candidate显得没必要,因为三个类可以共享许多成员变量,如term,log_store等等。因此在cornerstone中抽象出raft_server这一个类,而raf......
  • json-server详细模拟GET、POST、DELETE等接口数据教程
    引言在前端开发过程中,我们经常需要在后端API尚未就绪的情况下模拟接口数据。json-server是一个强大而灵活的工具,可以帮助我们快速创建一个模拟的RESTfulAPI。本文将详细介绍如何使用json-server来模拟GET、POST、PUT、PATCH、DELETE等常用的HTTP方法,以及如何处理复杂的数......
  • SpringBoot 项目的方法名是否添加@Transactional注解,以及SQL语句(SQLServer数据库)是
    项目改用SpringDataJDBC并手动配置DataSource之后,@Transactional注解一直不起作用。这两天研究了一下,注解不起作用,主要是没有配置TransactionManager的事,配置完TransactionManager之后,@Transactional注解就起作用了。但是配置完又发现,用jdbcTemplate.queryForList()方法执......
  • Sql Server数据库监听 c#代码
    usingAnfiniL.SqlServerTools.Data;usingSqlServerTools;usingSqlServerTools.Data;usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Net;usingSystem.Text;namespacewindowsApiAcitonSimulation.Help{publiccla......
  • MySQL的server层和存储引擎层是如何交互的(处理SQL)
    假设表结构createtabletest(aintnotnull,bintnotnull,cintnotnull,primarykey(a),uniquekeyidx_b(b))Engine=InnoDB;select*fromtestwhereb<2andc<3;MySQL服务层会将SQL解析,将where条件交给存储引擎层。存储引擎层拿到where条件后,发现正好......
  • H3C UniServer R4900 G5创建 RAID卷【图解】
    正常开机,弹出选择按键选择Esc2.进入此页面下拉可以换成中文语言(能看懂英文的忽略)3.开启RAID功能,选择高级→平台配置→PCH配置→PCHSATA配置→将配置SATA为改成RAID,然后F4保存并重启4.重启之后继续选择Esc进入BIOS→选择高级→动态设备配置菜单→选择自己的阵列→......
  • 使用KEPServerEX一键开启基于CODESYS的PLC数据采集
    KEPServerEXCODESYS以太网驱动提供了一种连接CODESYSPLC的方式,CODESYS是一个PLC运行和开发环境,被许多自动化行业的PLC品牌所使用。该驱动驱动对于制药、食品和饮料以及包装行业特别有用,在这些行业中,需要从工厂中的控制器收集数据,用于多个应用,包括可追溯性、监控和控制以及工厂范......