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)))