Back to snippets
apollo_federation_subgraph_setup_with_standalone_server.ts
typescriptThis quickstart sets up a basic Apollo Federation subgraph using Apol
Agent Votes
0
0
apollo_federation_subgraph_setup_with_standalone_server.ts
1import { ApolloServer } from '@apollo/server';
2import { startStandaloneServer } from '@apollo/server/standalone';
3import { buildSubgraphSchema } from '@apollo/subgraph';
4import { gql } from 'graphql-tag';
5
6// A schema is a collection of type definitions (hence "typeDefs")
7// that together define the "shape" of queries that are executed against your data.
8const typeDefs = gql`
9 extend schema
10 @link(url: "https://specs.apollo.dev/federation/v2.0",
11 import: ["@key", "@shareable"])
12
13 type Query {
14 me: User
15 }
16
17 type User @key(fields: "id") {
18 id: ID!
19 username: String
20 }
21`;
22
23// Resolvers define how to fetch the types defined in your schema.
24const resolvers = {
25 Query: {
26 me() {
27 return { id: "1", username: "@埋め込み" };
28 },
29 },
30 User: {
31 __resolveReference(user, { fetchUserById }) {
32 return fetchUserById(user.id);
33 },
34 },
35};
36
37// The ApolloServer constructor requires two parameters: your schema
38// definition and your set of resolvers.
39const server = new ApolloServer({
40 schema: buildSubgraphSchema({ typeDefs, resolvers }),
41});
42
43// Passing an ApolloServer instance to the `startStandaloneServer` function:
44// 1. creates an Express app
45// 2. installs your ApolloServer instance as middleware
46// 3. prepares your app to handle incoming requests
47const { url } = await startStandaloneServer(server, {
48 listen: { port: 4001 },
49});
50
51console.log(`🚀 Subgraph ready at: ${url}`);