Sails基礎之Helpers進階

進階例子參考

sails generate helper read-file
npm install fs --save

read-file.js:

const fs = require('fs');

module.exports = {

  friendlyName: 'Read file',

  description: 'Read file',

  extendedDescription: 'Set file path to read file',

  inputs: {
    resolvePath: {
      type: 'string',
      description: 'The file resolve path',
      required: true
    }
  },

  exits: {
    success: {
      outputFriendlyName: 'File data',
      outputDescription: 'File data.',
    },

    noFileFound: {
      description: 'Could not find file.'
    },

    ioError: {
      description: 'IO exception.'
    }
  },


  fn: async function (inputs, exits) {

    let resolvePath = inputs.resolvePath;

    let absolutePath = await sails.helpers.getAbsolutePath.with({
      resolvePath: resolvePath
    });
    if(fs.existsSync(absolutePath)){
      fs.readFile(absolutePath, (err, buf) => {
        if (err) {
          sails.log(err);
          throw 'ioError'
        }
        return exits.success(buf.toString());
      });

    } else {
      throw 'noFileFound';
    }
  }

};

TestController.js:

module.exports = {

    testReadFile: async function(req, res){
        let resolvePath = req.param('path');
        let data = await sails.helpers.readFile.with({
            resolvePath: resolvePath
        });
        return res.json({
            data: data
        });
    }
};

config/routes.js:

'get /api/test/readFile': 'TestController.testReadFile'

測試如下:
http://127.0.0.1:1337/api/test/readFile?path=package.json

http://127.0.0.1:1337/api/test/readFile?path=package.bson

該例子主要包含了多個exit,並通過在邏輯執行中的判斷選擇採用哪種exit方式。

Exceptions異常處理

異常處理分爲intercept(中斷)和tolerate(容忍),使用方法如下:

intercept

testReadFile: async function(req, res){
        let resolvePath = req.param('path');
        let data = await sails.helpers.readFile.with({
            resolvePath: resolvePath
        }).intercept('noFileFound', () => {
            return new Error('Inconceivably, no file were found for read.');
        });
        return res.json({
            data: data
        });
    }


tolerate

testReadFile: async function(req, res){
        let resolvePath = req.param('path');
        let data = await sails.helpers.readFile.with({
            resolvePath: resolvePath
        }).tolerate('noFileFound', () => {
            sails.log.verbose('Worth noting: no file were found for read.');
        });
        return res.json({
            data: data
        });
    }

直接傳遞req對象

如果你設計的helper用於解析req對象的headers,可以直接傳遞req對象,方法如下:

inputs: {

  req: {
    type: 'ref',
    description: 'The current incoming request (req).',
    required: true
  }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章