Example using NX, GraphQL and Prisma to connect to a MongoDB database
An example repo created to demonstrate NX with some cool tools to make life easy:
- A simple component library using Storybook
- A MongoDB database managed via Prisma
- A client project that uses the component library and Apollo Client to display data
- An Apollo Server service that connects to the database and responds to GraphQL requests
- Full type generation for queries and mutations using GraphQL Code Generator
-
Clone the repo
-
Install root dependencies (via Yarn or NPM)
npm install
-
Create a root
.env
file that includes aDATABASE_URL
string - this will be the MongoDB URL and should include the username and password permissions for a user. It should look something like this:#if connecting to a remote DB DATABASE_URL="mongodb+srv://<USERNAME>:<PASSWORD>@<URL>.mongodb.net/<COLLECTION_NAME>"
# if connecting to the local DB replicate set established by the docker-compose up set this URL and set up your /etc/host file to recognise mongo1, mongo2 and mongo3 DATABASE_URL="mongodb://localhost:30001,localhost:30002,localhost:30003/dev?replicaSet=my-replica-set" # in /etc/hosts 127.0.0.1 mongo1 127.0.0.1 mongo2 127.0.0.1 mongo3
-
Generate the CRUD resolvers for the GraphQL server
npm run prisma:generate
To start individual apps, use the nx serve
command:
npx nx serve mongo-graphql
npx nx serve frontend
You can also start both apps and run them in parallel like this:
npx nx run-many --target=serve --projects=frontend,mongo-graphql --parallel=2
Similar commands can be used to run other tools, such as jest or storybook:
npx nx storybook design-system
npx nx test frontend
To view the dependancy graph:
npx nx graph
npx nx affected:graph #if you want to see the affected apps/libs highlighted
affected
can also be used to run commands on all affected projects:
npx nx affected:test
If any changes are made to the queries (.gql
files), re-generate the types by using:
sh npm run codegen