thinkjs 簡單搭建api服務

安裝 ThinkJS 命令

$ npm install -g think-cli

安裝完成后,系統(tǒng)中會有 thinkjs 命令(可以通過 thinkjs -V 查看 think-cli 的版本號,此版本號非 thinkjs 的版本號)。如果找不到這個命令,請確認環(huán)境變量是否正確

創(chuàng)建項目

執(zhí)行 thinkjs new [project_name] 來創(chuàng)建項目,如:

$ thinkjs new demo;
$ cd demo;
$ npm install; 
$ npm start; 

打開瀏覽器訪問 http://127.0.0.1:8360/,如果是在遠程機器上創(chuàng)建的項目,需要把 IP 換成對應的地址。

安裝調(diào)試工具ndb

npm install -g ndb 

首先要確保你的 Node.js 環(huán)境 >= 8.0.0,然后使用 npm install 就可以非常方便的完成安裝。由于 ndb 依賴 Puppeteer 安裝過程中會去下載 Chromium 所以下載過程可能會有一定的時間,請各位同學耐心等待。如果有碰上權(quán)限問題官方提示可以嘗試增加 --unsafe-perm=true --allow-root 參數(shù)解決。
使用調(diào)試工具調(diào)試
在vscode命令行工具里輸入

ndb npm run

即可打開ndb調(diào)試頁面

ndb

熟悉chrome dev調(diào)試的對此不會陌生
進入頁面后在左側(cè)菜單中找到npm scripts菜單,在次菜單下鼠標放到start上后會出現(xiàn)開始三角按鈕,點擊按鈕即運行調(diào)試模式.
可以嘗試在執(zhí)行代碼中打斷點,和chrome dev效果一致.
同時可以修改代碼,保存即可同步代碼.

開始添加業(yè)務邏輯

我們要做一個logger上報和查詢的api

  1. 連接mysql
    src->config->adapter.js 文件下修改代碼,連接sql字符串
/**
 * model adapter config
 * @type {Object}
 */
exports.model = {
  type: 'mysql',
  common: {
    logConnect: isDev,
    logSql: isDev,
    logger: msg => think.logger.info(msg)
  },
  mysql: {
    handle: mysql,
    database: 'thinkjsplus',
    prefix: '',
    encoding: 'utf8',
    host: '127.0.0.1',
    port: '3306',
    user: 'root',
    password: 'root',
    dateStrings: true
  }
};
  1. 在mysql中新建database 名為thinkjsplus
    創(chuàng)建table,并寫入初始數(shù)據(jù)
-- ----------------------------
-- Table structure for `thinkjsplus_logger`
-- ----------------------------
DROP TABLE IF EXISTS `thinkjsplus_logger`;
-- auto-generated definition
create table thinkjsplus_logger
(
  id   int auto_increment,
  user varchar(100) null
  comment '用戶信息',
  port varchar(200) null
  comment '端口信息',
  info varchar(500) null
  comment 'log 信息',
  time datetime     not null
  comment '上報時間',
  constraint thinkjsplus_logger_id_uindex
  unique (id)
)
  comment 'web error logger';

alter table thinkjsplus_logger
  add primary key (id);


-- ----------------------------
-- Records of thinkjsplus_logger
-- ----------------------------
INSERT INTO `thinkjsplus_logger` VALUES ('admin', 'localhost','test');
INSERT INTO `thinkjsplus_logger` VALUES ('user1', 'www.example','test');

創(chuàng)建 Controller

使用命令

thinkjs controller logger

之后再src/controller文件夾下會生成logger.js文件,我們的邏輯就寫在這里面

const Base = require('./base.js');
const moment = require('moment');//引用了moment庫,需要安裝npm install --save moment

module.exports = class extends Base {
  async listAction() {
    if (this.isPost) {
      let data = await this.model('thinkjsplus_logger').select();
      return this.success(data);
    } else {
      return this.json(null);
    }
  }

  async addAction() {
    let data = this.post();
    data.time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
    if (think.isEmpty(data.id)) {
     
      let res=null;
      try {
         //保存
        res = await this.model('thinkjsplus_logger').add(data).catch(err => {
          return think.isError(err) ? err : new Error(err);
        });
      } catch (e) {
        return this.fail(1000, e);
      }

      if (think.isError(res)) {
        return this.fail(1000, res.message);
      }
      if (res) {
        this.success(true);
      } else {
        this.success(true);
      }
    } else {
      //更新
      let res = await this.model('thinkjsplus_logger').update(data);
      if (res) {
        this.success(true);
      } else {
        this.success(true);
      }
    }
  }
};

請求測試

  1. 使用postman發(fā)送添加請求
// url server為全局變量 http://localhost:8360/
{{server}}logger/add
//body json
{
    "user":"wwmin",
    "port":"localhost",
    "info":"test"
}

在ndb的listAction中打斷點進行調(diào)試,一切順利就會看到返回結(jié)果為true

  1. 使用postman發(fā)送查詢請求
// url server為全局變量 http://localhost:8360/
{{server}}logger/list

請求方式為post,但是沒有參數(shù)
在ndb的listAction中打斷點進行調(diào)試,一切順利就會看到返回結(jié)果為 list 對象.
說明接口調(diào)試完成.

終于將thinkjs跑通了接口api,為以后的搭建后臺api鋪平了道路,當然里面還有許多沒考慮到的地方,比如 權(quán)限驗證,service服務,model,middleware,logic,extend等方面都沒有涉及,在這之后會進一步研究,并將此文繼續(xù)補充完整.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容