0.0.9 • Published 5 years ago

httpf v0.0.9

Weekly downloads
6
License
-
Repository
-
Last release
5 years ago

httpf

用于express,将http请求翻译成函数调用.

httpf可以接受url以及body中的参数。使用body时需要在前面加上

app.use(bodyParser.urlencoded());

Usage

app.all('/f1', httpf({p1:'string', p2:'number', p3:'date'}, function(p1, p2, p3, cb) {
    assert(typeof p1==='string'
    && typeof p2 === 'number'
    && p3 instanceof Date);
    
    return 'ok';
}));
app.all('/f2', httpf(['string', 'number', 'date', 'callback'], function(p1, p2, p3, cb) {
    assert(typeof p1==='string'
    && typeof p2 === 'number'
    && p3 instanceof Date);
    cb(null,'ok');
}));

支持的type

  • 所有 javascript 定义的type,ie, string, number, boolean, etc
  • date, 日期, 任何可以被new Date()识别的字符串。ie. time=2015-1-2 15:00
  • object, 对象,JSON.parse可以识别的字符串 ie obj={"a":1, "o":{}}

callback

如果在opt中包含callback,f的最后一个参数将会是回调函数,给客户端的返回值需要从这里传出。 e.g

app.all('/f',httpf({callback:1}, function(callback) {
    callback(null, 'ok');
}));

否则直接通过return给出返回值

no_return

如果含有no_return标记,httpf不向res中写入任何数据,此时f需要自行管理向客户端返回数据。这通常用于下载文件。 e.g

app.use('/dl', httpf({name:'string', no_return:true}, function(name) {
    require('fs').createReadStream(name).pipe(this.res);
}));

httpf.text(str,statusCode)

app.all('/f',httpf(function() {
    return httpf.text('hello!');
}));

这个函数用来构造text/html类型的返回值

客户端接受到的值

除非定义了no_return, 总是一个json字符串

{"result":"ok"|"error", message:"something", ...}

result='ok' 代表函数成功,返回值一般在message中,或者就是这个对象本身

result='error', 执行失败,错误在message中。

未来的改变

上述返回值在下一版会被修改成

{err:"something wrong"} || {message:"ok", ...}

Updates

0.0.6 增加了跨域支持,CDN不再会缓冲httpf返回的数据

从0.0.7开始。支持jsonp调用。但是不能自定义$.ajax({jsonp})这个关键字,必须是默认的'callback'。

0.0.9

5 years ago

0.0.8

6 years ago