React学习笔记7-快速构建一个动态全球独角兽列表网站(2)

本文介绍如何使用Sails.js快速构建后端服务,包括模型创建、RESTful API自动生成、数据导入及定制API等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端API开发

通过Sails.js可以快速构建一个后端的服务。

建模

通过下面这条命令来新建一个model:

sails generate api Unicorns

建模,修改Unicorns.js:

module.exports = {

  attributes: {

    name: { type: 'string', required: true },
    country: { type: 'string' },
    last_funding_on: { type: 'string', columnType: 'date' },
    total_equity_funding: { type: 'number' },
    founded_on: { type: 'number' },
    category: { type: 'string' },
    post_money_val: { type: 'number' }
  },

};

对于数据的CRUD操作,Sails.js的Bluprint立刻自动生成了RESTFul的API。
可以通过http://localhost:1337/Unicorns来访问服务。

数据库中导入数据

通过下面这条命令来新建一个action:

sails generate action import

import.js:

const data = require('../../tools/unicorns');

module.exports = {


  friendlyName: 'Import',


  description: 'Import something.',


  inputs: {

  },


  exits: {

  },


  fn: async function (inputs) {

    const unicorns = [...data];

    unicorns.forEach(
        u => {
            delete u.logo_url;
            delete u.permalink;
            delete u.tag_page;
            delete u.unicorn_bday;
            delete u.unicorn_exit;
            delete u.rumored;
            delete u.valuation_change;
            delete u.date_of_valuation;

            if (u.total_equity_funding === null) {
              u.total_equity_funding = 0;
            }

        }
    );

    const result = await Unicorns.createEach(unicorns);
    return result;

  }


};

修改route.js文件:

'/api/v1/import' : {action: 'import'},

通过http://localhost:1337/api/v1/import可以从准备的测试数据中自动把数据导入到数据库。

定制api

通过下面这条命令来新建一个action:

sails generate action count

count.js:

module.exports = {


  friendlyName: 'Count',


  description: 'Count something.',


  inputs: {

  },


  exits: {

  },


  fn: async function (inputs) {

    const result = await Unicorns.count();

    return { total: result };

  }


};

修改route.js文件:

 '/api/v1/count' : {action: 'count'}

通过http://localhost:1337/api/v1/count可以获取到数据的条数。

全部API清单:

  1. Unicorns CRUD:
    http://localhost:1337/unicorns

还可以通过/unicorns?skip=xxx&limit=xxx来获取一定量的数据。

  1. 导入测试数据:
    http://localhost:1337/api/v1/Import

  2. 数据条数:
    http://localhost:1337/api/v1/count

项目代码

https://github.com/rangwei/unicorns-sails

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值