这里的播放页面是不含播放器的,主要是为了用GraphQL
index.js
const fs = require('fs');
const app = new (require('koa'));
const mount = require('koa-mount');
const static = require('koa-static');
const graphqlHTTP = require('koa-graphql');
app.use(
// 给koa-graphql传一个graphql的协议文件,就会自动帮你生成graphql-api
mount('/api', graphqlHTTP({
schema: require('./schema')
}))
)
app.use(
mount('/static', static(`${__dirname}/source/static`))
)
app.use(
mount('/', async (ctx) => {
ctx.status = 200;
ctx.body = fs.readFileSync(`${__dirname}/source/index.htm`, 'utf-8')
})
)
// module.exports = app;
app.listen(3000)
schema.js
const { graphql, buildSchema } = require('graphql')
const mockDatabase = require('./mock-database') // 假数据,是个array
const schema = buildSchema(`
type Comment {
id: Int
avatar: String
name: String
isTop: Boolean
content: String
publishDate: String
commentNum: Int
praiseNum: Int
}
type Query {
comment: [Comment]
}
type Mutation {
praise(id: Int): Int
}
`)
schema.getQueryType().getFields().comment.resolve = () => {
return Object.keys(mockDatabase).map(key=> {
return mockDatabase[key];
})
}
// Mutation处理
schema.getMutationType().getFields().praise.resolve = (args0, { id }) => {
mockDatabase[id].praiseNum++;
return mockDatabase[id].praiseNum
}
module.exports = schema;
静态文件部分代码省略了。
点击“点赞发起的请求”:
fetch("./api", {
method: "POST",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
"query": "mutation { praise(id: " + $bindtarget.getAttribute("data-id") + ") }"
})
}).then(res => res.json())
.then(res => {
$bindtarget.querySelector('span').innerHTML = res.data.praise
})
发起的请求的参数是:mutation { praise(id)}