diff --git a/software/03.Prisma/README.md b/software/03.Prisma/README.md index e2b78787..fbb3a0df 100644 --- a/software/03.Prisma/README.md +++ b/software/03.Prisma/README.md @@ -1,256 +1,112 @@ -# Workshop 3 - GraphQL API with Prisma2 +# Initial Setup: PostgreSQL and Express.js with Prisma -In this workshop, we will learn how to create GraphQL APIs using [Prisma2](https://www.prisma.io/), Nexus-Prisma and Apollo. +## Step 1: Installing Necessary Tools -## Step 0: initialization +Make sure Node.js and npm are installed on your machine. Then, install the following dependencies: -All the required information to install the workshop dependencies are available in [SETUP.md](./SETUP.md). +1. PostgreSQL: Download and install PostgreSQL from the official website. +2. Create a PostgreSQL database (e.g., `workshop`). -## Step 1: Retrieve posts +## Step 2: Initializing the Express.js Project -You saw in the setup a query that retrieves all users from the database. Now, do the same thing but to get all the posts. +1. Create a new folder for your project and open it in the terminal. +2. Run the following commands: -Create the `getPosts` function: -- It doesn't take any parameters -- It returns a list of all the posts in the database. - -All the necessary information about the database schema are in the `schema.prisma`. - -## Step 2: Create - Read - Update - Delete - -You've seen how data fetching with Prisma works, you'll now implement classic CRUD functions (see the title of this step). - -> If needed, refer to this [page](https://www.prisma.io/docs/getting-started/quickstart-typescript#write-data-into-the-database) to see basics operations with Prisma. You will need the keyword `where`. - -Create the `addUser` function: -- It takes in parameters `name` and `email`, the name and email of the user that will be created -- It adds the user to the database -- It returns the created userQuery - -Create the `addPost` function: -- It takes in parameters `title` and `content`, the title and content of the post, as well as `authorId`, the id of the user who will be the author of the post. -- It adds the post to the database (this post must be connected to the `authorId` received in parameter) -- It returns the created post - -Create the `getPostsByUsers` function: -- It takes in parameter `authorId`, the id of the user whose posts we want to retrieve -- It returns the list of posts of the requested user - -Create the `removeUser` function: -- It takes in parameter `id`, the id of the user that will be deleted -- It returns the user who has been deleted - -Create the `removePost` function: -- It takes in parameter `id`, the id of the post that will be deleted -- It returns the post that has been deleted - -## Step 3: Apollo Server and Nexus - -Prisma allows us to retrieve data from the database, but we then have to allow the users to retrieve this data. We will use [GraphQL Nexus](https://nexusjs.org/) and [Apollo server](https://www.apollographql.com/docs/apollo-server/) for this purpose. - -You will have to install new packages to do this: - -Steps to install Apollo and Nexus -- Create a new folder named `prisma-nexus-gql`. -- Download the [zip](./src/3.prisma.zip) from our repo. -- Extract the zip into your `prisma-nexus-gql`. -- Run `npm install` in your `prisma-nexus-gql` folder to install the new dependencies. -- Run `npm run migration` to migrate the prisma schema in the database. -- Run `npm run generate` to generate prisma client and graphql queries. +```bash +npm init -y +npm install express +``` -> You should see a warning message when you generate the schema. +## Step 3: Installing Prisma -If you subsequently run `npm start`, you will get a warning, which is normal. For the server to run properly, you have to add an `objectType` that defines the `Post` table in the `entities` folder. -An example of the `User` table is present in the folder, it's up to you to do `Post`. +Install Prisma as a development dependency: -> [Nexus model documentation](https://nexusjs.org/docs/plugins/prisma/overview) +```bash +npm install prisma --save-dev +``` -## Step 4: Setting up the CRUD with Nexus +Initialize Prisma by running the following command: -Now that your models are well defined, you can implement the data manipulations seen in Step 2, but this time with Nexus. +```bash +npx prisma init +``` -You will build in your schema a `Query` object that will contain the methods to read data and a `Mutation` object that will contain the methods to edit data (add / update / delete). +Follow the instructions to set up the connection to your PostgreSQL database. Make sure to use the connection information for the database you created earlier. -- For them to take effect, you will have to add these objects to the `type` field of your `schema` defined in `schema.ts`. +## Step 4: Creating a Simple Express.js Application -> Nexus documentation about [Queries](https://nexusjs.org/docs/api/query-field) and [Mutations](https://nexusjs.org/docs/api/mutation-field) -> The `resolve` field is where you will call prisma to query data inside the database +Create an index.js file in the root of your project. -To test the queries/mutations you are going to set up, you can go to to use a playground that lets you to test your server. +In index.js, set up Express.js to start a basic HTTP server: -We already gave the `getUsers` query and the `signupUser` mutation to let you see what the syntax looks like, and make it easier to create the next ones. -Below, we also give you examples to test your queries and mutations. +```javascript -Create the following queries: -- `getPosts`: returns the list of all posts in the database -- `getPostsByUser`: returns the list of all the posts of a user thanks to its `authorId`. -- `getPublishedPosts`: returns a list of all posts that are published. +const express = require('express'); +const app = express(); +const PORT = 3000; -Create the following mutations: -- `writeDraft`: creates a post with a `title`, a `content` and the `authorId` of its author. By default it is not published. -- `publishDraft`: publishes a post whose `id` is specified. -- `deletePost`: deletes a post whose `id` is specified. +app.get('/', (req, res) => { + res.send('Hello, world!'); +}); -Here are some examples of queries and mutations you can execute in the playground to test your functions -
See Query and Mutations (Click me!) +app.listen(PORT, () => { + console.log(`Server is running on port ${PORT}`); +}); +``` -## Query +## Step 5: Using Prisma in Your Application -### getUsers +In the prisma folder, open the schema.prisma file. +Define your database models. For example: -```graphql -query { - getUsers { - id - name - email - posts { - id - title - } - } +```prisma +model User { + id Int @id @default(autoincrement()) + username String + email String @unique + posts Post[] } -``` -### getPosts - -```graphql -query { - getPosts { - id - title - content - published - author { - id - name - email - } - } +model Post { + id Int @id @default(autoincrement()) + title String + content String + author User @relation(fields: [authorId], references: [id]) + authorId Int } ``` -### getPostsByUser +Run the following command to generate the corresponding Prisma files: -```graphql -query { - getPostsByUser(authorId: ) { - id - title - content - } -} +```bash +npx prisma generate ``` -> Note: you must replace **** with the current id of an author. - -### getPublishedPosts - -```graphql -query { - getPublishedPosts { - id - title - content - published - author { - id - name - email - } - } -} -``` -> NOTE: you will get an empty array if you have not called the mutation to publish a post yet. - -## Mutations -### signupUser +Use Prisma in your Express.js application: -```graphql -mutation { - signupUser( - name: "Paul" - email: "paul@prisma.io" - ) { - id - } -} -``` +```javascript +const express = require('express'); +const { PrismaClient } = require('@prisma/client'); -### writeDraft - -```graphql -mutation { - writeDraft( - title: "Join the Prisma Slack" - content: "https://slack.prisma.io" - authorId: "__AUTHOR_ID__" - ) { - id - published - } -} -``` +const app = express(); +const prisma = new PrismaClient(); +const PORT = 3000; -### publishDraft +app.get('/', async (req, res) => { + const users = await prisma.user.findMany(); + res.json(users); +}); -```graphql -mutation { - publishDraft(id: __POST_ID__) { - id - published - } -} +app.listen(PORT, () => { + console.log(`Server is running on port ${PORT}`); +}); ``` -### deletePost -```graphql -mutation { - deletePost(id: __POST_ID__) { - id - title - } -} -``` +## Step 6: Running the Application -
- -## Bonus - -If you finished the workshop and don't know what to do until the end, you can try to: -- Use the prisma studio to manipulate your db with a web interface. Run `npx prisma studio --experimental --port 3000` -- Use the Nexus CRUD functions to drastically reduce your code, see the [documentation](https://nexusjs.org/docs/plugins/prisma/overview#example) -- Update the database model to add new columns and tables, and your API with it. - -## Authors - -| [
Paul Monnery](https://github.com/PaulMonnery) | [
Naoufel Berrada](https://github.com/nowlow) | [
Cyril de Lajudie](https://github.com/Axoloot) | [
Tom Chauveau](https://github.com/TomChv) -| :---: | :---: | :---: | :---: | -

-Organization -

-
-

- - LinkedIn logo - - - Instagram logo - - - Twitter logo - - - Discord logo - -

-

- - Website logo - -

- -> 🚀 Don't hesitate to follow us on our different networks, and put a star 🌟 on `PoC's` repositories. +Start the Express.js server: +```bash +node index.js +``` \ No newline at end of file diff --git a/software/03.Prisma/SETUP.md b/software/03.Prisma/SETUP.md deleted file mode 100644 index bf468995..00000000 --- a/software/03.Prisma/SETUP.md +++ /dev/null @@ -1,105 +0,0 @@ -# Setup - -## Installation - -You will need: -- [node (version 10 minimum)](https://github.com/nodejs/node): JavaScript runtime -- [npm](https://www.npmjs.com/): node package manager -- [npx](https://www.npmjs.com/package/npx): node_modules command executor - -To install node: -- under fedora: `sudo dnf install nodejs`. -- under ubuntu: `sudo apt install nodejs npm`. - -Then `sudo npm install -g npx`. - -To start using prisma, just run the following command: -```bash -curl https://codeload.github.com/prisma/quickstart/tar.gz/master | tar -xz --strip=2 quickstart-master/javascript/starter -``` - -This will download a small project provided by Prisma developers to help you understand the basics. Just enter your newly created `starter` folder and run: - -```sh -npm install -``` - -There are 5 important files in the `stater` folder: - -- `package.json`: lists the npm dependencies. -- `prisma/schema.prisma`: the Prisma schema file that defines the database models. -- `prisma/.env`: Sets the database connection with its URL as environment variable. -- `prisma/dev.db`: SQLite database file. -- `script.js`: File in which you will code your functions. - -You can also display the database via a web interface: -```sh -npx prisma studio -``` -💡 If you have an error while running this command, try to update the `prisma` packages: -```sh -npm add -D prisma@3.15.0 && npm add @prisma/client@3.15.0 -``` - -## Prisma in javascript code - -We will see line by line what is in the `script.js` file: -```js -const { PrismaClient } = require("@prisma/client"); -``` - -Node will look for the `@prisma/client` dependency in the `node_modules` folder (created with `npm install`). - -
- -```js -const prisma = new PrismaClient(); -``` -This line creates a new instance of a prisma client. - -
- -```js -async function main() { - // ... you will write your Prisma Client queries here -} -``` -Here we create an asynchronous function. We will code inside later. -> if you need more information on how async functions work, [read this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) - -
- -```js -main() - .catch(e => { - throw e - }); - .finally(async () => { - await prisma.$disconnect() - }); -``` - -Finally, this part of the code calls our `main` function, displays a message if an error has occurred and disconnects the prisma client once all actions have been completed. - -Currently, if you do `npm run dev`, nothing should happen. We will prepare the basics for the next exercises, so add the following line to your main function: -```js -console.log("getUsers:\n", await getUsers()) -``` - -and add above your `main` function: -```js -function getUsers() { - return prisma.user.findMany(); -} -``` - -If you run `npm run dev` again, you should have this output: -```js -getUsers: - [ { id: 1, email: 'sarah@prisma.io', name: 'Sarah' }, - { id: 2, email: 'maria@prisma.io', name: 'Maria' } ] -``` - -**If you have finished all these steps, you can now move on to the exercises**. - -[Go back to the exercises](./README.md) diff --git a/software/03.Prisma/package.json b/software/03.Prisma/package.json deleted file mode 100644 index e750a1d5..00000000 --- a/software/03.Prisma/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "typescript-javascript", - "scripts": { - "dev": "node ./src/server.js" - }, - "dependencies": { - "@nexus/schema": "0.13.1", - "@prisma/client": "2.0.0-beta.2", - "apollo-server": "2.14.2", - "graphql": "14.6.0", - "nexus-prisma": "0.12.0" - }, - "devDependencies": { - "@prisma/cli": "2.0.0-beta.2" - }, - "prettier": { - "singleQuote": true, - "semi": false, - "trailingComma": "all" - }, - "engines": { - "node": ">=10.0.0" - } -} \ No newline at end of file diff --git a/software/03.Prisma/src/3.prisma.zip b/software/03.Prisma/src/3.prisma.zip deleted file mode 100644 index eb2ae5a9..00000000 Binary files a/software/03.Prisma/src/3.prisma.zip and /dev/null differ