node封装博客园接口

目的:将博客园提供的api 封装成我们可以想要的json数据类型

依赖库:axios xml2js

直接上代码:

import fetch from '../utils/fetch'
import * as xml2js from 'xml2js'
const parser = new xml2js.Parser({ explicitArray: false, ignoreAttrs: true })

class Blog {
  async getBlogList(ctx) {
    try {
      const { page, limit } = ctx.request.query
      const xml = await fetch({ url: `http://wcf.open.cnblogs.com/blog/u/lyxverycool/posts/${page}/${limit}` })
      let blogLists;
      parser.parseString(xml, (err, res) => {
        blogLists = res.feed
      })
      ctx.body = {
        status: '1',
        type: 'success_query_blogList_all',
        message: 'success',
        data: blogLists
      }
    } catch (err) {
      ctx.body = {
        status: '0',
        type: 'error_query_blogList_all',
        message: err.toString()
      }
    }
  }
  async getBlogDetail(ctx) {
    try {
      const { id } = ctx.request.query
      const blogDetail = await fetch({ url: `http://wcf.open.cnblogs.com/blog/post/body/${id}` })
      ctx.body = {
        status: '1',
        type: 'success_query_blogDetail',
        message: 'success',
        data: blogDetail
      }
    } catch (err) {
      ctx.body = {
        status: '0',
        type: 'error_query_blogDetail',
        message: err.toString()
      }
    }
  }
}

export default new Blog()

  

posted @ 2019-05-14 11:24  李元夕cool  阅读(485)  评论(0编辑  收藏  举报