Merging Multiple TypeDefs — Organizing with Apollo Federation

Why Multiple TypeDefs

Basic Guidance to Organizing A Federated Service

.
├── graphql
│ ├── index.ts
│ ├── schema.ts
│ ├── resolvers
│ │ ├── account
│ │ ├── mutation
│ │ ├── query
│ │ └── user
| │ └── index.ts
│ └── typeDefs
| ├── account
│ └── user
| └── index.ts
└── server.ts
// ./graphql/typeDefs/user.tsimport { gql } from "apollo-server-express";export const UserTypes = gql`
type User {
first_name: String
last_name: String
}

...Other Types and Inputs
extend type Query {
...
}
extend type Mutation {
...
}
`;
// ./graphql/typeDefs/user.tsexport const UserTypes = gql`extend type Account @key(fields: "_id") {
_id: ObjectID! @external
email: String! @external
loginUser(loginUserInput: LoginUserInput): LoginUserResponse
@requires(fields: "_id email")
users(getUsersInput: GetUsersInput!): GetUsersResponse
@requires(fields: "_id")
}
...Other Types and Inputsextend type Query {
...
}
extend type Mutation {
...
}
`;
// server.ts
import { ApolloServer } from "apollo-server";
import { schema } from "./graphql";
const apolloServer = new ApolloServer({
schema
});
apolloServer
.listen({ port })
.then(({ url }) => console.log(`Service ready at ${url}`));
// schema.ts
import { buildSubgraphSchema } from "@apollo/federation";
import { UserTypeDefs, AccountTypeDefs } from "./typeDefs";
import { UserResolvers, AccountResolvers } from "./resolvers";
export const schema = buildSubgraphSchema([
{ typeDefs: UserTypeDefs, resolvers: UserResolvers },
{ typeDefs: AccountTypeDefs, resolvers: AccountResolvers },
]);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store