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

Sails基础之Helpers进阶

http://127.0.0.1:1337/api/test/readFile?path=package.bson
Sails基础之Helpers进阶
该例子主要包含了多个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
        });
    }

Sails基础之Helpers进阶
Sails基础之Helpers进阶

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
        });
    }

Sails基础之Helpers进阶

直接传递req对象

如果你设计的helper用于解析req对象的headers,可以直接传递req对象,方法如下:

inputs: {

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

}