0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js&GraphQL part4 ~ Prisma APIとAsync/Await ~

Last updated at Posted at 2019-03-29

Prisma API と Promise Chain

以下のような Type を定義して、新しくPostを作成する。

datamodel.prisma
type User {
  id: ID! @unique
  name: String!
  email: String! @unique
  posts : [Post!]!
}

type Post {
    id: ID! @unique
    title: String!
    body: String!
    published: Boolean!
    author: User!
}
prisma.js
import { Prisma } from 'prisma-binding'

// prisma: Prisma configuration object
// Prisma: Its constructor creates connection to Prisma endpoint
const prisma = new Prisma({
    typeDefs: 'src/generated/prisma.graphql',
    endpoint: 'http://xxx:4466',
})

/**
 * prismaオブジェクトは基本操作を行う4つのオブジェクトをもつ
 * 1. prisma.query
 * 2. prisma.mutation
 * 3. prisma.subscription
 * 4. prisma.exists
 *
 * それぞれクエリを行うためのメソッドを持っており2つの引数を必要とする
 * 1. Operation Argument
 * 2. Selection Set
 *
 * Promiseをreturnする
 */

// async はPromiseを返します
const createPostForUser = async (authorId, data) => {

    // 新しい Post を作成する
    // その際に、その Post を作成した User を authorId で指定する
    // 作成した Post の id を return させる
    const post = await prisma.mutation.createPost({
        data: {
            ...data,
            author: {
                connect: {
                    id: authorId
                }
            }
        }
    }, '{ id }')

    // 上で使用した authorId と一致する id をもつ Usedr を取得する
    const user = await prisma.query.user({
        where: {
            id: authorId
        }
    }, '{ id name email posts { id title published } }')

    // async なので Promise として resolve する
    return user
}

// 新しく作成する Post の情報と、Post を作成した User の id を引数に渡してメソッドを呼ぶ
// Promise が返ってくるので .then でつなげられる
createPostForUser("cjttne201003s0720tlslaqz8", {
    title: "Great Book",
    body: "Very GOOOOOOD!",
    published: true
})
.then( data => console.log(JSON.stringify(data, undefined, 2)))
出力
{
  "id": "cjttne201003s0720tlslaqz8",
  "posts": [
    {
      "id": "cjttsih2a006r0720nesau8xd",
      "title": "Great Book",
      "body": "Very GOOOOOOD!",
      "published": true
    }
  ]
}

Async/Await でスッキリす。

本当は2回もawait使う必要なかったけども。

prisma.js(await1回ver)
import { Prisma } from 'prisma-binding'

const prisma = new Prisma({
    typeDefs: 'src/generated/prisma.graphql',
    endpoint: 'http://xxx:4466',
})

const createPostForUser = async (authorId, data) => {
    const post = await prisma.mutation.createPost({
        data: {
            ...data,
            author: {
                connect: {
                    id: authorId
                }
            }
        }
    }, '{ author { id name email posts { id title published } } }')
    return post.author
}

createPostForUser("cjttne201003s0720tlslaqz8", {
    title: "Great Book",
    body: "Very GOOOOOOD!",
    published: true
})
.then( data => console.log(JSON.stringify(data, undefined, 2)))
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?