API操作

此章介绍用js开发API操作,在jmms中,一个API操作对应一个.js文件。

Hello World

创建app/operations/hello.js文件:

/**
 * Say hello.
 * @GET
 * @param {string} who
 * @return {string} The hello message.
 */
function hello(who) {
    return 'Hello ' + who;
}

保存后,浏览器访问http://localhost:8080/hello

{
    "code": "BAD_REQUEST",
    "message": "Validation failed -> who : 请输入内容"
}

提示需要输入参数,重新访问http://localhost:8080/hello?who=world

"Hello world"

函数定义

注意

  • .js文件中需要定义一个对应API操作的函数。
  • 代码必须写在函数体内,函数体外的内容无效

不支持以下写法

const util = require('util');
function _() {
    doSomething();
}

function doSomething() {}

需要写成:

function _() {
    const util = require('util');

    doSomething();

    function doSomething() {}
}

函数名

函数名可以是有意义的名字,也可以是无意义的函数名(以_开头的函数名不作为Swagger文档的operationId)。

无意义的函数名:

function _() {}

有意义的函数名:

function updateUserProfile() {}

函数参数

在注释中定义的输入参数可以在函数体中直接访问。

/**
  * @param {string} who
  */
  function _() {
    return 'Hello ' + who;
  }

在函数体中直接引用操作的输入方法,可以不在函数中定义

输入参数也可以在函数中定义:

/**
  * @param {string} who
  */
  function _(who) {
    return 'Hello ' + who;
  }

函数结果返回

  • 没有返回值
/**
 */
function _() {
    //do something, no return value.
}
  • 使用return返回
/**
  * @return {integer} The affected rows.
  */
function _() {
    return 100;
}
  • 使用return Response.xxx()返回(这是jmms推荐的方式)
/**
  *  @param {integer} id
  *  @param {string} newPassword
  *  @return <200> {integer} The affected rows.
  *  @return <404> If the user not exists.
  */ 
  function _() {
    const user = require('User');
    const affected = user.exec('update user set password = :newPassword where id = :id, $params);
    if(affected > 0) {
        return Response.ok(affected);
    }else{
        return Response.notFound('User ' + id + ' not found');
    }
  }
Bingosoft            updated 2018-07-23
上一篇:使用Javascript开发 下一篇:全局变量

results matching ""

    No results matching ""