这里的播放页面是不含播放器的,主要是为了用GraphQL
    index.js

    1. const fs = require('fs');
    2. const app = new (require('koa'));
    3. const mount = require('koa-mount');
    4. const static = require('koa-static');
    5. const graphqlHTTP = require('koa-graphql');
    6. app.use(
    7. // 给koa-graphql传一个graphql的协议文件,就会自动帮你生成graphql-api
    8. mount('/api', graphqlHTTP({
    9. schema: require('./schema')
    10. }))
    11. )
    12. app.use(
    13. mount('/static', static(`${__dirname}/source/static`))
    14. )
    15. app.use(
    16. mount('/', async (ctx) => {
    17. ctx.status = 200;
    18. ctx.body = fs.readFileSync(`${__dirname}/source/index.htm`, 'utf-8')
    19. })
    20. )
    21. // module.exports = app;
    22. app.listen(3000)

    schema.js

    1. const { graphql, buildSchema } = require('graphql')
    2. const mockDatabase = require('./mock-database') // 假数据,是个array
    3. const schema = buildSchema(`
    4. type Comment {
    5. id: Int
    6. avatar: String
    7. name: String
    8. isTop: Boolean
    9. content: String
    10. publishDate: String
    11. commentNum: Int
    12. praiseNum: Int
    13. }
    14. type Query {
    15. comment: [Comment]
    16. }
    17. type Mutation {
    18. praise(id: Int): Int
    19. }
    20. `)
    21. schema.getQueryType().getFields().comment.resolve = () => {
    22. return Object.keys(mockDatabase).map(key=> {
    23. return mockDatabase[key];
    24. })
    25. }
    26. // Mutation处理
    27. schema.getMutationType().getFields().praise.resolve = (args0, { id }) => {
    28. mockDatabase[id].praiseNum++;
    29. return mockDatabase[id].praiseNum
    30. }
    31. module.exports = schema;

    静态文件部分代码省略了。

    点击“点赞发起的请求”:

    1. fetch("./api", {
    2. method: "POST",
    3. headers: {
    4. 'content-type': 'application/json'
    5. },
    6. body: JSON.stringify({
    7. "query": "mutation { praise(id: " + $bindtarget.getAttribute("data-id") + ") }"
    8. })
    9. }).then(res => res.json())
    10. .then(res => {
    11. $bindtarget.querySelector('span').innerHTML = res.data.praise
    12. })

    发起的请求的参数是:mutation { praise(id)}