how to seperate schema and resolvers and merage them apollo-server-express - graphql

I have User and Post typeDefs/resolvers I want to separate them so I can get
User.schema.js
User.resolver.js
Post.schema.js
Post.resolver.js
link.Schema.js
link.resolvers.js
how to do this and merge them to get just one typeDefs/resolvers to pass it to
const server = new ApolloServer({
typeDefs,
resolvers
});

I have been using the merge-graphql-schemas package for the type definition and lodash deep object merge function for the resolvers like so:
import merge from "lodash/merge"
import { mergeTypes } from "merge-graphql-schemas"
import UserSchema from "./User.schema"
import UserResolvers from "./User.resolvers"
import PostSchema from "./Post.schema"
import PostResolvers from "./Post.resolvers"
import LinkSchema from "./Link.schema"
import LinkResolvers from "./Link.resolvers"
const typeDefs = mergeTypes([UserSchema, PostSchema, LinkSchema])
const resolvers = merge(UserResolvers, PostResolvers, LinkResolvers)
const server = new ApolloServer({
typeDefs,
resolvers
});
EDIT: please note that graphql-tools's mergeSchemas is now the recommended way of schema stitching with apollo server now.

There is no need for some more dependency for merging the types, as graphql-tools are fine for them.
Have a look https://github.com/techyaura/graphqlNodeMongodb-server/tree/master/src/gql, if it helps.
I have two files todo.types.js & user.type.js in the repo https://github.com/techyaura/graphqlNodeMongodb-server/tree/master/src/gql/types & I am simply concatenating them & that's working fine.
NOTE: I am not using APOLLO GRAPHQL, instead using express-graphql simply

Related

Graphql tools - mergeTypeDefs sort alphabetically

I'm using the following code to merge 2 typesDefs to one:
import { mergeTypeDefs } from '#graphql-tools/merge';
import topicsTypes from '../modules/topics/typeDefs';
import contentTypes from '../modules/content/typeDefs';
const types = [contentTypes, topicsTypes];
export default mergeTypeDefs(types)
When I run graphql-schema-linter I get an error:
22:1 The fields of object type Query should be sorted in alphabetical order. Expected sorting: contentAccessTokenByUUID, documentContent, documentTopics type-fields-sorted-alphabetically
I tried changing the order of the types in the array to [topicsTypes, contentTypes];
But I get the same error, how can I force mergeTypeDefs to merge the defs alphabetically?
Try to import your schemas as shown below
Depending on your file extension edit the following
import { mergeTypeDefs } from '#graphql-tools/merge';
import { loadFilesSync } from '#graphql-tools/load-files';
const typesArray = loadFilesSync('./schema', {
extensions: ['gql'],
});
const typeDefs = mergeTypeDefs(typesArray, { throwOnConflict: true, sort: true });
export default typeDefs;
If you want to check out the doc
New mergeTypeDefs-routine from https://www.graphql-tools.com/docs/migration-from-merge-graphql-schemas/
Also might be helpful to check out this https://www.graphql-tools.com/docs/api/interfaces/merge_src.Config#throwonconflict

Best Practice for Folder Structure For Resolvers and TypeDefs resolve ambiguity

I am working on best practices for folder structure on an apollo-graphql project. Right now I have a graphql folder that contains both a Resolvers and Schema Folder, this is to keep everything separate. However, Within my Resolvers folder I want a new Typescript file for each Typedef. (See photo)
[![enter image description here][2]][2]
However, in my Index file I put in this
/src/graphql/resolvers/index.ts
export *from "./Category"
export * from "./Product"
However, I get the following error
"./Category" has already exported a member named 'resolvers'. Consider explicitly re-exporting to resolve the ambiguity."
What is the best way to approach this issue so that I can have everything separated out, but still only have to import one line into my ApolloServer
src/index.ts
import { ApolloServer } from 'apollo-server'
import { context } from './graphql/context'
import {typeDefs} from "./graphql/Schema/index"
import {resolvers} from "./graphql/resolvers/index"
new ApolloServer({ resolvers, typeDefs, context: context }).listen(
{ port: 4000 },
() =>
console.log(`
🚀 Server ready at: http://localhost:4000`))

How to use custom directives graphql-modules with apollo

I need help with custom directives when using graphql-modules library. Have no idea where to place my custom directives so it is combined with overall schema
I would like to post answer from Discord community, from user Maapteh.
here it the quote from him
in our app with old version we had everything in common module. We
kept that approach partly when using the latest version of modules.
See some parts of our codebase:
import { ApolloServer, SchemaDirectiveVisitor } from
'apollo-server-express';
const schema = AppModule.createSchemaForApollo();
SchemaDirectiveVisitor.visitSchemaDirectives(schema, {
isMember: IsMemberDirective,
deprecated: isDeprecated,
...SNIP... });
as you can see we create the schema we pass eventually to the apollo
server (example using apollo). We add our generic directives like so.
The schema for them is in our common module. Read further...
For common scalars we added a common module. With their schema (so in
schema directory we also have the directives schemas) and their
resolver.
const typeDefsArray = loadFilesSync(${__dirname}/schema/*.graphql, {
useRequire: true, }); const typeDefs = mergeTypeDefs(typeDefsArray, { useSchemaDefinition: false });
const resolverFunctions = {
ImageUrl: ImageUrlType,
PageSize: PageSizeType,
Date: DateResolver,
...SNIP... };
export const CommonModule = createModule({
id: 'common',
typeDefs: typeDefs,
resolvers: resolverFunctions, });
hope it helps you
https://discord.com/channels/625400653321076807/631489837416841253/832595211166548049

prisma.yml could not be found

I am trying to generate schema for my prisma data model while at the same time using secrets to restrict prisma access. After running prisma delete and prisma deploy, I run the command graphql get-schema -p prisma and get the following error message:
✖ prisma/prisma.yml could not be found.
Is there something wrong I am doing in my .graphqlconfig or how I am listing my prisma.yml? Thanks.
.graphqlconfig:
{
"projects": {
"prisma": {
"schemaPath": "generated/prisma.graphql",
"extensions": {
"prisma": "prisma/prisma.yml",
"endpoints": {
"default": "http://localhost:4466"
}
}
}
}
}
prisma/prisma.yml:
endpoint: http://localhost:4466
datamodel: datamodel.prisma
secret: 'secretFoo'
index.js:
import http from 'http';
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import resolvers from './resolvers';
import schema from './generated/prisma.graphql';
import { Prisma } from 'prisma-binding';
const prisma = new Prisma({
endpoint: 'http://localhost:4466',
secret: 'secretFoo',
typeDefs: 'server/generated/prisma.graphql',
});
const server = new ApolloServer({
context: {
prisma,
},
resolvers,
typeDefs: schema,
});
const app = express();
server.applyMiddleware({ app });
const PORT = 5000;
const httpServer = http.createServer(app);
server.installSubscriptionHandlers(httpServer);
httpServer.listen(PORT, () => {
console.log(`Server ready at http://localhost:${PORT}${server.graphqlPath}`);
console.log(`Subscriptions ready at ws://localhost:${PORT}${server.subscriptionsPath}`);
});
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => server.stop());
}
You can generate a schema directly from your prisma.yml file, by adding the following to the file:
generate:
- generator: graphql-schema
output: ./generated/prisma.graphql
Then you can refer your .graphqlconfig to the generated file:
projects:
prisma:
schemaPath: generated/prisma.graphql
extensions:
endpoints:
dev: http://localhost:4466
You would generally restrict access to the management functionality of your endpoint through the Prisma docker-compose file (managementApiSecret in PRISMA_CONFIG). Then when you run commands like prisma deploy you would need to pass the appropriate environment variables through either the --env-file flag, or by having a dotenv file in the root of your application's directory (you also need the dotenv package installed in package.json.
Another way to secure your endpoint is to disable the GraphQL Playground altogether. I believe Apollo Server does this automatically when NODE_ENV is set to production, although you can do it explicitly with:
const server = new ApolloServer({
context: {
prisma,
},
resolvers,
typeDefs: schema,
playground: false, // <- Here
});
I'm sorry, I don't think this directly answered your question, but it may assist either way.

after migrating to apollo client 3.0, using "withApollo" hoc throwing could not find client context error

TLDR; managed to pull up a codesandbox with the issue, please have a look here.
things were working fine while using react-apollo 2.5, now we have started the process of migrating to 3.0.
snapshot of the relevant portion of my package.json
"#apollo/client": "^3.0.0-beta.19",
"#apollo/react-components": "^3.1.3",
"#apollo/react-hoc": "^3.1.3",
Now I am getting the below error
Could not find "client" in the context of ApolloConsumer. Wrap the root component in an <ApolloProvider>.
The outermost component of my App is indeed the ApolloProvider,
the way I import ApolloProvider after migration is shown below
import { ApolloProvider } from "#apollo/client";
also I have taken care to import the withApollo hoc from "#apollo/react-hoc" as mentioned in migration docs.
Isn't migration just changing the versions in package.json and imports? or is there anything specific I need to know when creating the apollo client instance?
Please find below, the code used for creating client instance
import { ApolloClient, HttpLink, InMemoryCache } from '#apollo/client';
const cache = new InMemoryCache();
const client = new ApolloClient({
link: new HttpLink({
uri: process.env.REACT_APP_GRAPHQLURL,
}),
cache,
connectToDevTools: true
});
According to the migration docs, you shouldn't import withApollo hoc from #apollo/react-hoc
You should use hoc package from #apollo/client
import { withApollo } from "#apollo/client/react/hoc";
https://www.apollographql.com/docs/react/migrating/apollo-client-3-migration/#apolloreact-hoc-and-apolloreact-components

Resources