Skip to content
This repository has been archived by the owner on Jan 2, 2023. It is now read-only.

Commit

Permalink
Adds support for file uploads and form bodies via formidable
Browse files Browse the repository at this point in the history
  • Loading branch information
segphault committed Mar 14, 2017
1 parent 249580c commit 3d7b2aa
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 20 deletions.
18 changes: 15 additions & 3 deletions examples/simple/routes.yaml
Expand Up @@ -49,6 +49,16 @@ route:
settings:
action: >
({a: 1, b: 2, c: 3})
- path: /filetest
method: post
settings:
parameters:
- in: body
name: test
- in: body
name: asdf
action: >
({"asdf": params.asdf, "test": params.test.name})
- path: /realtime
method: get
settings:
Expand Down Expand Up @@ -76,9 +86,11 @@ route:
parameters:
- in: body
name: test
schema:
$ref: test
action: r.expr([1,2,3]).map(r.row.mul(2))
type: number
- in: body
name: qwerty
type: number
action: r.expr([params.test, 2,3]).map(r.row.mul(params.qwerty))
- path: /test/fellowship
method: get
settings:
Expand Down
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -10,6 +10,7 @@
},
"dependencies": {
"ajv": "^3.5.3",
"formidable": "^1.1.1",
"graphql": "^0.7.0",
"jwt-simple": "^0.5.0",
"minimist": "^1.2.0",
Expand Down
2 changes: 1 addition & 1 deletion src/requests.js
Expand Up @@ -53,7 +53,7 @@ class RequestHandler {
if (param.schema === "@")
param.schema = input.collection.schema;

output[param.name] = param.in === "body" ?
output[param.name] = param.in === "body" && param.schema ?
this.processBody(param, input) :
this.processParam(param, input);
}
Expand Down
30 changes: 14 additions & 16 deletions src/server.js
@@ -1,6 +1,14 @@
const {parse} = require("url");
const {Server} = require("node-static");
const {info, error} = require("./utils");
const formidable = require("formidable");

const bodyParser = request =>
new Promise((resolve, reject) => {
let form = new formidable.IncomingForm();
form.parse(request, (err, fields, files) =>
err ? reject(err) : resolve({fields, files}))
});

class ServerRequest {
constructor(request, response) {
Expand All @@ -13,23 +21,13 @@ class ServerRequest {
this.ip = request.headers["x-forwarded-for"] ||
request.connection.remoteAddress;

this.params = {
query: this.url.query,
header: this.request.headers,
body: null
}
this.params = {query: this.url.query, header: this.request.headers};
}

parse() {
let body = "";
return new Promise((resolve, reject) => {
if (this.params.body) return resolve(this);
this.request.on("data", chunk => body += chunk);
this.request.on("end", () => {
this.params.body = body ? JSON.parse(body) : {};
resolve(this);
});
});

async parse() {
let {fields, files} = await bodyParser(this.request);
this.params.body = Object.assign({}, fields, files);
return this;
}

send(data) {
Expand Down

0 comments on commit 3d7b2aa

Please sign in to comment.