Express后台实现数据分页功能

2018-01-29  本文已影响0人  jebirth

问题:网站如果被大量用户使用时,服务器要完成大量发送数据和插入数据任务。
解决:为了保持服务的友好性,并保持合理的响应时间,在返回数据时,用分页功能来返回部分。经常使用的数据,可以使用内存来缓存,使其能快速发送(本文就不讨论了)。

本文内容如下:
1.抓取数据
    # Primary fields
    title = Field()
    view = Field()
    updated = Field()
    image_urls = Field()
    link = Field()

    # Calculated fields
    images = Field()
    location = Field()

    # Housekeeping fields
    url = Field()
    project = Field()
    spider = Field()
    server = Field()
    date = Field()
rules = (
        Rule(LinkExtractor(restrict_xpaths='//a[contains(@class, "buttonright")]')),
        Rule(LinkExtractor(restrict_xpaths='//a[contains(@class, "result_link")]'), callback='parse_item')
    )
2.保存数据
import fs from "fs";
const Data = JSON.parse(fs.readFileSync("./posts/items.json"));

//筛选数据
const posts = Data.map((post) => {
    if(post.hasOwnProperty("updated")){
        return Object.assign({}, {
            title: post.title[0],
            link: post.url[0],
            view: post.view[0],
            updated: post.updated[0]
        })
    }else{
        return {}
    } 
});

//去掉{},抓取的数据保存到postsData中
const postsData = posts.filter((value) => {
    return Object.keys(value).length
})
const postsSchema = new mongoose.Schema({
  title: { type: String },
  link: { type: String },
  view: { type: String },
  updated: { type: String }
});
const Posts = mongoose.model("Post", postsSchema);
postsData.map(value => {
  let item = new Posts(value);
  item.save((error, result) => {
    if (error) {
      throw error;
    }
  });
});
3.实现分页功能
app.use(expressPaginate.middleware(10, 50));
postsSchema.plugin(mongoosePaginate);
const Posts = mongoose.model("Post", postsSchema);
Posts.paginate(
      {},
      {
        page: req.query.page,
        limit: req.query.limit
      },
      (error, result) => {
        if (error) {
          res.writeHead(500, { "Content-Type": "text/plain" });
          res.end("Internal server error");
          return;
        }
        res.setHeader("Content-Type", "application/json");
        res.send({
          object: "contacts",
          page_count: result.pages,
          result: result
        });
      }
    );
5. 不足之处

要先转换在Posts项目中,抓取数据保存到item.json中,才运行服务器。鄙人不才,不知在Package.json如何实现。

6.参考网站

关注微信号:gh_93f4c7518be0

上一篇下一篇

猜你喜欢

热点阅读