Skip to content

Commit

Permalink
chore: update
Browse files Browse the repository at this point in the history
  • Loading branch information
dalisoft committed Mar 3, 2020
1 parent e1d731f commit 9e1fd19
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# These are supported funding model platforms

# github: dalisoft
patreon: nanoexpress # Replace with a single Patreon username
patreon: dalisoft # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
Expand Down
54 changes: 51 additions & 3 deletions examples/extend.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,69 @@
import nanoexpress from '../src/nanoexpress.js';
import Route from '../src/Route.js';
import qs from 'querystring';

const app = nanoexpress({
json_spaces: 2
});

class HeaderSupportedRoute extends Route {
async middleware(req) {
async middleware_header(req) {
req.headers = {};

req.forEach((key, value) => {
req.headers[key] = value;
});
}
async middleware_body(req, res) {
if (req.method === 'POST' || req.method === 'PUT') {
const contentType = req.headers['content-type'];

let buffer = Buffer.allocUnsafe(0);
await new Promise((resolve, reject) => {
res.onAborted(reject);
res.onData((chunk, isLast) => {
buffer = Buffer.concat([buffer, Buffer.from(chunk)]);

if (isLast) {
if (contentType && contentType.indexOf('/json') !== -1) {
res.writeHeader('Content-Type', contentType);
req.body = JSON.parse(buffer.toString('utf8'));
} else if (
contentType &&
contentType.indexOf('/x-www-form-urlencoded') !== -1
) {
req.body = qs.parse(buffer.toString('utf8'));
} else if (contentType && contentType.indexOf('/plain') !== -1) {
req.body = buffer.toString('utf8');
} else {
req.body = buffer;
}
resolve();
}
});
});
}
}
async middleware_query(req) {
const query = req.getQuery();

if (query) {
req.query = qs.parse(query);
}
}
onPrepare() {
const { _middlewares } = this;

if (_middlewares) {
_middlewares.unshift(this.middleware);
_middlewares.unshift(this.middleware_query);
_middlewares.unshift(this.middleware_header);
_middlewares.splice(_middlewares.length - 1, 0, this.middleware_body);
} else {
this._middlewares = [this.middleware];
this._middlewares = [
this.middleware_header,
this.middleware_query,
this.middleware_body
];
}
}
}
Expand All @@ -30,5 +75,8 @@ app.use(route);
route.get('/', async (req, res) => {
return res.send({ headers: req.headers });
});
route.post('/', async (req, res) => {
return res.send({ body: req.body });
});

app.listen(8000);

0 comments on commit 9e1fd19

Please sign in to comment.