UNPKG

lightappbuilder

Version:

Baidu AppBuilder api implemention

86 lines (80 loc) 2.79 kB
module.exports = function (req, res, next) { req.lightapp = { __proto__: exports, req: req, _referer: 'http://' + req.headers.host + req.url }; next(); }; var lightapp = exports; lightapp.file = { getQuota: function (cb) { this.request('GET', '/api/file.quota', cb).end(); }, download: function (path, cb, range) { this.request('GET', '/api/file' + path, cb, null, range && { Range: 'bytes=' + range[0] + '-' + range[1] }, true).end(); }, upload: function (path, data, cb, overwrite) { this.request('PUT', '/api/file' + path + (overwrite ? '?overwrite=true' : ''), cb, { 'Content-Length': data.length }).end(data); }, mkdir: function (path, cb) { this.request('PUT', '/api/file' + path + '?dir=true', cb, { 'Content-Length': 0 }).end(); }, pipe: function (path, overwrite) { var req = this.req, res = req.response; req.pipe(this.request(req.method, '/api/file' + path + (overwrite ? '?overwrite=true' : ''), function (err, tres) { if (err) { res.statusCode = 500; res.end(err.message); } else { res.writeHead(tres.statusCode, tres.headers); tres.pipe(res); } }, req.headers, true)); } }; 'query,get,keys,setString,set,unset,remove,clear,sync,addSitemap,removeSitemap,publish'.split(',') .forEach(function (name) { lightapp[name] = function () { var args = Array.prototype.slice.call(arguments), cb = args.pop(); if (typeof cb !== 'function') { args.push(cb); cb = console.log.bind(console); } // assert(typeof cb === 'function'); var data = new Buffer(JSON.stringify({ method: name, params: args })); this.request('POST', '/api', cb, { 'Content-Length': data.length }).end(data); }; }); lightapp.request = function (method, url, cb, headers, raw) { var HOST = 'lightapp.duapp.com'; var headers = headers || {}; headers.Referer = this._referer; headers.Host = HOST; return require('http').request({ method: method, host: HOST, path: url, headers: headers }, function (tres) { if (raw) { cb(null, tres); } else { var arr = []; tres.on('data', arr.push.bind(arr)).on('end', function () { cb(null, JSON.parse(Buffer.concat(arr))); }); } }).on('error', cb); }