Last active
December 15, 2016 17:44
-
-
Save dlindenkreuz/9ae51ff36421ca13cad3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Fetchr middleware for koa | |
* | |
* Translate Fetchr.middleware() from express.js to koa | |
* This is pretty rough and might be buggy but it does the job nicely for me at the moment. | |
* | |
* Tested with fetchr v0.5.14 | |
*/ | |
export default function () { | |
return function * (next) { | |
let ctx = this | |
// construct expressjs-like request | |
const modifiedReq = { | |
path: ctx.request.url, | |
method: ctx.request.method, | |
body: ctx.request.body | |
} | |
yield new Promise((resolve, reject) => { | |
// mock an expressjs response that modifies the actual koa response | |
const modifiedRes = { | |
status(code) { | |
ctx.response.status = code | |
return this | |
}, | |
json(data) { | |
ctx.response.body = data | |
/** | |
* cheap trick: fetchr does not support promises yet and does not return anything | |
* when fetching is successful. however, req.json is always called last when fetches are successful | |
* so let's just inject the promise resolve here. no need to touch the fetchr library at all. | |
*/ | |
resolve() | |
return this | |
}, | |
set(headers) { | |
ctx.response.headers = headers | |
return this | |
} | |
} | |
Fetchr.middleware()(modifiedReq, modifiedRes, err => { | |
if (err) { | |
throw err | |
} | |
else resolve() | |
}) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment