Skip to content

Commit

Permalink
Update README.md, Update eslint
Browse files Browse the repository at this point in the history
  • Loading branch information
iamnapo committed Aug 18, 2019
1 parent d8eec25 commit 929597d
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 76 deletions.
44 changes: 34 additions & 10 deletions README.md
Expand Up @@ -13,24 +13,48 @@ $ npm i just-the-cors micro
## Example

```js
const { send } = require('micro');
const { router, get } = require('microrouter');
const cors = require('just-the-cors');
const { send } = require("micro");
const { router, get } = require("microrouter");
const cors = require("just-the-cors");

const getWithCors = (path, handler) => get(path, cors(handler));

const hello = cors((req, res) => send(res, 200, { message: 'Hello 1!' }));
const hello = cors((req, res) => send(res, 200, { message: "Hello 1!" }));
const hello2 = (req, res) => {
cors(req, res);
return send(res, 200, { message: 'Hello 2!' });
return send(res, 200, { message: "Hello 2!" });
};
const hello3 = (req, res) => send(res, 200, { message: 'Hello 3!' });
const hello3 = (req, res) => send(res, 200, { message: "Hello 3!" });

module.exports = router(
get('/hello/1', hello),
get('/hello/2', hello2),
get('/hello/3', cors(hello3)),
getWithCors('/*', (req, res) => send(res, 200, { message: 'Hello in general!' })),
get("/hello/1", hello),
get("/hello/2", hello2),
get("/hello/3", cors(hello3)),
getWithCors("/*", (req, res) => send(res, 200, { message: "Hello in general!" })),
);
```

### Note

> If you don't supply the `res` object as a second argument, `cors` does nothing!
```js
const { router, get } = require("microrouter");
const cors = require("just-the-cors");

const hello1 = (req) => {
cors(req); // Does nothing!
return "Hello 1";
};

const hello2 = (req, res) => {
cors(req, res);
return "Hello 2";
};

module.exports = router(
get("/hello1", hello1), // "Access-Control-Allow-Origin": ❌
get("/hello2", hello2), // "Access-Control-Allow-Origin": ✅
);
```

Expand Down
36 changes: 18 additions & 18 deletions index.js
@@ -1,16 +1,16 @@
module.exports = (...args) => {
if (args.length === 1 && typeof args[0] === 'function') { // It's the handler
if (args.length === 1 && typeof args[0] === "function") {
const cb = args[0];
return (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");

if (req.method.toUpperCase() === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
res.setHeader('Access-Control-Request-Headers', 'Vary');
const reqHeaders = req.headers['access-control-request-headers'];
if (reqHeaders && reqHeaders.length) res.setHeader('Access-Control-Allow-Headers', reqHeaders);
res.setHeader('Content-Length', '0');
if (req.method.toUpperCase() === "OPTIONS") {
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE");
res.setHeader("Access-Control-Request-Headers", "Vary");
const reqHeaders = req.headers["access-control-request-headers"];
if (reqHeaders && reqHeaders.length) res.setHeader("Access-Control-Allow-Headers", reqHeaders);
res.setHeader("Content-Length", "0");
res.statusCode = 204;
return res.end();
}
Expand All @@ -19,17 +19,17 @@ module.exports = (...args) => {
};
}

const [req, res = { setHeader: () => {}, statusCode: null, end: () => {} }] = args;
const [req, res = { setHeader: () => {}, end: () => {} }] = args;

res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");

if (req.method.toUpperCase() === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
res.setHeader('Access-Control-Request-Headers', 'Vary');
const reqHeaders = req.headers['access-control-request-headers'];
if (reqHeaders && reqHeaders.length) res.setHeader('Access-Control-Allow-Headers', reqHeaders);
res.setHeader('Content-Length', '0');
if (req.method.toUpperCase() === "OPTIONS") {
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE");
res.setHeader("Access-Control-Request-Headers", "Vary");
const reqHeaders = req.headers["access-control-request-headers"];
if (reqHeaders && reqHeaders.length) res.setHeader("Access-Control-Allow-Headers", reqHeaders);
res.setHeader("Content-Length", "0");
res.statusCode = 204;
return res.end();
}
Expand Down
11 changes: 6 additions & 5 deletions package.json
Expand Up @@ -36,16 +36,17 @@
},
"dependencies": {},
"devDependencies": {
"ava": "^2.2.0",
"ava": "^2.3.0",
"babel-eslint": "^10.0.2",
"eslint": "^6.1.0",
"eslint-config-airbnb": "^17.1.1",
"eslint-config-iamnapo": "^1.0.5",
"eslint-config-airbnb": "^18.0.1",
"eslint-config-iamnapo": "^1.2.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-react": "^7.14.2",
"eslint-plugin-react": "^7.14.3",
"eslint-plugin-react-hooks": "^1.7.0",
"got": "^9.6.0",
"husky": "^3.0.1",
"husky": "^3.0.4",
"micro": "^9.3.4",
"microrouter": "^3.1.3",
"test-listen": "^1.1.0"
Expand Down
86 changes: 43 additions & 43 deletions tests/unit.test.js
@@ -1,105 +1,105 @@
import test from 'ava';
import micro from 'micro';
import listen from 'test-listen';
import got from 'got';
import { router, get } from 'microrouter';
import test from "ava";
import micro from "micro";
import listen from "test-listen";
import got from "got";
import { router, get } from "microrouter";

import cors from '..';
import cors from "..";

const server = fn => listen(micro(fn));
const server = (fn) => listen(micro(fn));

test('different routes', async (t) => {
test("different routes", async (t) => {
const routes = router(
get('/foo', cors(() => ({ name: 'foo' }))),
get('/bar', cors(() => ({ name: 'bar' }))),
get("/foo", cors(() => ({ name: "foo" }))),
get("/bar", cors(() => ({ name: "bar" }))),
);

const url = await server(routes);
const { body: fooGet } = await got.get(`${url}/foo`, { json: true });
const { body: barGet } = await got.get(`${url}/bar`, { json: true });

t.is(fooGet.name, 'foo');
t.is(barGet.name, 'bar');
t.is(fooGet.name, "foo");
t.is(barGet.name, "bar");
});

test('routes with params and query', async (t) => {
const hello = req => `Hello ${req.params.msg} ${req.query.time}`;
test("routes with params and query", async (t) => {
const hello = (req) => `Hello ${req.params.msg} ${req.query.time}`;

const routes = router(get('/hello/:msg', cors(hello)));
const routes = router(get("/hello/:msg", cors(hello)));

const url = await server(routes);
const { body } = await got.get(`${url}/hello/world?time=now`);

t.is(body, 'Hello world now');
t.is(body, "Hello world now");
});

test('routes with underline', async (t) => {
const routes = router(get('/foo_bar', cors(() => 'Hello with underline')));
test("routes with underline", async (t) => {
const routes = router(get("/foo_bar", cors(() => "Hello with underline")));

const url = await server(routes);
const { body } = await got.get(`${url}/foo_bar`);

t.is(body, 'Hello with underline');
t.is(body, "Hello with underline");
});

test('async handlers', async (t) => {
test("async handlers", async (t) => {
const hello = (req) => {
cors(req);
return Promise.resolve(`Hello ${req.params.msg} ${req.query.time}`);
};

const routes = router(get('/hello/:msg', hello));
const routes = router(get("/hello/:msg", hello));

const url = await server(routes);
const { body } = await got.get(`${url}/hello/world?time=now`);

t.is(body, 'Hello world now');
t.is(body, "Hello world now");
});

test('composed routes', async (t) => {
const fooRouter = cors(router(get('/foo', () => 'Hello foo')));
const barRouter = cors(router(get('/bar', () => 'Hello bar')));
test("composed routes", async (t) => {
const fooRouter = cors(router(get("/foo", () => "Hello foo")));
const barRouter = cors(router(get("/bar", () => "Hello bar")));

const routes = router(fooRouter, barRouter);

const url = await server(routes);
const { body: fooResponse } = await got.get(`${url}/foo`);
const { body: barResponse } = await got.get(`${url}/bar`);

t.is(fooResponse, 'Hello foo');
t.is(barResponse, 'Hello bar');
t.is(fooResponse, "Hello foo");
t.is(barResponse, "Hello bar");
});

test('multiple matching routes', async (t) => {
const withPath = cors(() => 'Hello world');
const withParam = cors(() => t.fail('Clashing route should not have been called'));
test("multiple matching routes", async (t) => {
const withPath = cors(() => "Hello world");
const withParam = cors(() => t.fail("Clashing route should not have been called"));

const routes = router(get('/path', withPath), get('/:param', withParam));
const routes = router(get("/path", withPath), get("/:param", withParam));

const url = await server(routes);
const { body } = await got.get(`${url}/path`);

t.is(body, 'Hello world');
t.is(body, "Hello world");
});

test('multiple matching async routes', async (t) => {
test("multiple matching async routes", async (t) => {
const withPath = (req, res) => {
cors(req, res);
return micro.send(res, 200, 'Hello world');
return micro.send(res, 200, "Hello world");
};
const withParam = cors(() => t.fail('Clashing route should not have been called'));
const withParam = cors(() => t.fail("Clashing route should not have been called"));

const routes = router(get('/path', withPath), get('/:param', withParam));
const routes = router(get("/path", withPath), get("/:param", withParam));

const url = await server(routes);
const { body } = await got.get(`${url}/path`);

t.is(body, 'Hello world');
t.is(body, "Hello world");
});

test('works with cors', async (t) => {
const routesBefore = router(get('/', () => ({ ok: true })));
const routesAfter = router(get('/', cors(() => ({ ok: true }))));
test("works with cors", async (t) => {
const routesBefore = router(get("/", () => ({ ok: true })));
const routesAfter = router(get("/", cors(() => ({ ok: true }))));

const urlBefore = await server(routesBefore);
const urlAfter = await server(routesAfter);
Expand All @@ -108,7 +108,7 @@ test('works with cors', async (t) => {

t.true(bodyBefore.ok);
t.true(bodyAfter.ok);
t.true(!Object.prototype.hasOwnProperty.call(headersBefore, 'access-control-allow-origin'));
t.true(Object.prototype.hasOwnProperty.call(headersAfter, 'access-control-allow-origin'));
t.is(headersAfter['access-control-allow-origin'], '*');
t.true(!Object.prototype.hasOwnProperty.call(headersBefore, "access-control-allow-origin"));
t.true(Object.prototype.hasOwnProperty.call(headersAfter, "access-control-allow-origin"));
t.is(headersAfter["access-control-allow-origin"], "*");
});

0 comments on commit 929597d

Please sign in to comment.