The title

The GraphQL framework Prisma of Xiaoxin Discovery

introduce

This is a new way to interact with the front and back ends, not necessarily the best, but it’s interesting, a way to give the front end people the freedom to control the database without the back end people developing SQL to read the database layer. Although it may not be able to solve all scenes, only good use, is likely to solve most of the scenes, reduce manpower, improve efficiency. Next generation ORM for Node.js and TypeScript. Mybatis ORM for Node.js and TypeScript To understand how to represent data in terms of objects, or diagrams.

Versions and Downloads

Node v15.5.1 NPM 7.3.0

reporter

I found in the research process, through the official TS tutorial, error has been reported, the reason is temporarily unknown, the main reason is not TS, in addition, it may be ali mirror problem, even if I delete it is not ok, so this tutorial, from the download of the official demo. We are divided into two steps. The first step is to build a script framework to try the charm of Prisma. The second step is to build a Node service, frame Express+Prisma, and provide it as a service to the front end.

The first building

The preparatory work

This time we use MySQL, database script address download address directly here, database name myDB, add a little creative.

CREATE DATABASE IF NOT EXISTS mydb DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;
USE mydb;

CREATE TABLE User (
  id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
  name VARCHAR(255),
  email VARCHAR(255) UNIQUE NOT NULL
);
CREATE TABLE Post (
  id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
  title VARCHAR(255) NOT NULL,
  createdAt TIMESTAMP NOT NULL DEFAULT now(),
  content TEXT,
  published BOOLEAN NOT NULL DEFAULT false,
  authorId INTEGER NOT NULL,
  FOREIGN KEY (authorId) REFERENCES User(id)
);
CREATE TABLE Profile (
  id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
  bio TEXT,
  userId INTEGER UNIQUE NOT NULL,
  FOREIGN KEY (userId) REFERENCES User(id)
);


    INSERT INTO `mydb`.`Post`(`title`, `createdAt`, `content`, `published`, `authorId`) VALUES ('Hello World', '2021-01-21 15:53:37', NULL, 0, 6);
    
    INSERT INTO `mydb`.`User`( `name`, `email`) VALUES ('Sarah', '[email protected]');
    INSERT INTO `mydb`.`User`(`name`, `email`) VALUES ('Maria', '[email protected]');

Copy the code

And then download the official demo, the address is www.prisma.io/docs/gettin… Download according to your environment. Mine is a MAC.

After the download is complete, there will be a start folder, structure as follows

Prisma # : prisma # : prisma # : prisma # : prisma # : prisma # : prisma # : prisma # : prisma # : prisma # : prisma # : prisma # So let him be quiet ------schema.prisma # The key things, the main configuration is here, data configuration, object logic --script.js # This use script, the rest of the run is hereCopy the code

The official version is SQLite, we need to make some changes, change it to me, you will be able to understand, I believe you. In Prisma, modify a. Env file (this is a hidden file, remember to unhide) with the following contents

DATABASE_URL = "mysql: / / root: [email protected]:3306 / mydb"Copy the code

Then edit schema.prisma and change provider to mysql

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}
Copy the code

Next let’s install dependency, ancestral command NPM install, I here is to remove ali mirror, the speed will be slower, because I am afraid ali mirror have no, cause some problems (don’t ask, ask is I really test for a long time)

When complete, executenpx prisma introspect

If NPM install@prisma /cli –save-dev does not work, try NPM install@prisma /cli –save-dev to install the environment.

Prisma is used to link to the database and generate the corresponding object, similar to mybatis-generator.

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  createdAt DateTime @default(now())
  content   String?
  published Boolean  @default(false)
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id])

  @@index([authorId], name: "authorId")
}

model User {
  id      Int      @id @default(autoincrement())
  name    String?
  email   String   @unique
  posts   Post[]
  Profile Profile?
}

model Profile {
  id     Int     @id @default(autoincrement())
  bio    String?
  userId Int     @unique
  User   User    @relation(fields: [userId], references: [id])
}

Copy the code

Here we need to change the content so that we can test it later. Just go to the code, you can just replace it. Main changes: User-> Aothor in Post, User-> User in Profile, Post -> posts, Profile -> Profile in User. Don’t ask why, ask because that’s what officials do, in fact I was wondering why not just change the name of the data field.

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  createdAt DateTime @default(now())
  content   String?
  published Boolean  @default(false)
  authorId  Int
  author      User     @relation(fields: [authorId], references: [id])

  @@index([authorId], name: "authorId")
}

model Profile {
  id     Int     @id @default(autoincrement())
  bio    String?
  userId Int     @unique
  user   User    @relation(fields: [userId], references: [id])
}

model User {
  id      Int      @id @default(autoincrement())
  name    String?
  email   String   @unique
  posts    Post[]
  profile Profile?
}
Copy the code

Then performnpx prisma generateTo generate clients. Notice that the generated file path is this/node_modules/.prisma/client/schema.prisma, the main effect is also the folder where the file is located, I understand.

Note that the key point is that every time you change schema.prisma, you need to run NPX prisma generate to generate the client.

Now that all the work is done, all that remains is to see the effect. Modify the contents of script.js.

const { PrismaClient } = require('@prisma/client') const prisma = new PrismaClient() // A `main` function so that you Can use async/await async function main() { Const allUsers = await prisma.user.findmany () console.log(allUsers)} main().catch(e => {throw e}) const allUsers = await prisma.user.findmany () console.log(allUsers)} main().catch(e => {throw e}) .finally(async () => { await prisma.$disconnect() })Copy the code

Then run NPM run dev

In fact, we have not done any logical code from the construction until now, we have relied on prisma framework to achieve, and now we will introduce the object, also graph way to describe the data, what will be the effect.

So let’s go ahead and modify script.js, and modify the main method, so that you can understand what’s going on with this data object, and what it does when it’s run, and here’s the object that describes the data that you want to insert, user, post, write the corresponding method, for example, create, The idea of GraphQL is to use objects and graphs to describe data and let Prisma manipulate it.

Address of the official API. Official API Tutorial

async function main() {
  await prisma.user.create({
    data: {
      name: "Alice",
      email: "[email protected]",
      posts: {
        create: { title: "Hello World" },
      },
      profile: {
        create: { bio:  "I like turtles" }
      }
    }
  })
  const allUsers = await prisma.user.findMany({
    include: { 
      posts: true,
      profile: true 
    },
  })
  console.dir(allUsers, { depth: null })
}
Copy the code

Run NPM run dev again

$NPM run dev > [email protected] dev > node./script.js [{id: 5, name: 'Sarah', email: '[email protected]', posts: [], profile: null }, { id: 6, name: 'Maria', email: '[email protected]', posts: [ { id: 4, title: 'Hello World', createdAt: 2021-01-21T15:53:37.000z, Content: NULL, Published: false, authorId: 6}], profile: null }, { id: 10, name: 'Alice', email: '[email protected]', posts: [ { id: 6, title: 'Hello World', createdAt: 2021-01-21T08:09:06.000z, Content: NULL, Published: false, authorId: 10}], profile: {id: 2, bio: 'I like turtles', userId: 10 } } ]Copy the code

Service-oriented construction

This step is changed to Express as a service, still using the official example, simple and direct.

Github address Link address

I am Mac is directly with the command, Windows can go to download

curl https://codeload.github.com/prisma/prisma-examples/tar.gz/latest | tar -xz --strip=2 prisma-examples-latest/javascript/rest-express
Copy the code

After downloading it, open it with Webstorm, and you’ll see that the directory structure is the same, with SRC and index.js in it. This is the main file we need to serve, and the interface is written here. Then follow the previous tutorial to modify the database, execute the corresponding commands, and modify schema.prisma. Here are the commands that need to be executed, the database and the schema.prisma are modified as in the previous tutorial.

$ npm install
$ npx prisma introspect 
$ npx prisma generate
Copy the code

If everything worked fine in the previous tutorial, this should work fine, and then we’ll go to SRC /index.js. And then let’s start it up, and the command is NPM run dev

You can try some of the official APIS to see how to describe data objects. Here I begin to transform it into a front-end direct control of data objects, through the interface to describe the realization of query and creation. Go straight to the code.

const express = require('express') const bodyParser = require('body-parser') const {PrismaClient} = require('@prisma/client') const prisma = new PrismaClient() const app = express() app.use(bodyParser.json()) app.get(`/user`, async (req, res) => { const result = await prisma.user.findMany({ ... req.body }) res.json(result) }) app.post(`/user`, async (req, res) => { const result = await prisma.user.create({ ... Req.body}) res.json(result)}) const server = app.listen(3000, () => console.log('🚀 server ready at: http://localhost:3000\n⭐️ See sample requests: http://pris.ly/e/ts/rest-express#3-using-the-rest-api',),)Copy the code

Postman tests this query, which is all prisma syntax, and then needs to match it with the schema. Prisma model to achieve the effect. You can try to describe some objects yourself, to get things.

So this is a new creation and I’m describing the corresponding creation object user data, and then I’m describing the posts-create object that does that. View the database.

This tutorial is just a brief introduction to the Prisma framework, and I will learn more about it later to see if it can form a fully usable service. I think it can.

Refer to the connection

Prisma officials got off to a fast start

I can choose the language, top right, I’ll say JS

Official Express Version

Chinese document

Official API Tutorial

That’s what you need to know how to use it, right