Skip to content

Commit

Permalink
Merge pull request #42 from syumai/update-deno-0.11.0
Browse files Browse the repository at this point in the history
Update to Deno 0.11.0
  • Loading branch information
syumai authored Jul 14, 2019
2 parents 530c0a3 + 76143a2 commit 90b7b7d
Show file tree
Hide file tree
Showing 9 changed files with 50 additions and 518 deletions.
11 changes: 2 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,14 +91,7 @@ app(

### Stop server

```ts
const api = app(get('/', () => 'hello'));

// Stop API after 5000ms.
setTimeout(() => {
api.close();
}, 5000);
```
- Currently dinatra has no feature to stop server.

## Flags

Expand All @@ -121,7 +114,7 @@ const app = new App(
false // option to enable static file hosting (boolean)
);

app.handle(get('/hello', () => 'hello'));
app.register(get('/hello', () => 'hello'));
```

## Response Types
Expand Down
2 changes: 1 addition & 1 deletion constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { args } = Deno;
import { parse } from 'https://deno.land/std/flags/mod.ts';
import { parse } from 'https://deno.land/std@v0.11.0/flags/mod.ts';

export const parsedArgs: {
p?: string;
Expand Down
2 changes: 1 addition & 1 deletion example/static_disabled/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import { defaultPort } from '../../constants.ts';
import { App, get } from '../../mod.ts';

const app = new App(defaultPort, false);
app.handle(get('/hello', () => 'hello'));
app.register(get('/hello', () => 'hello'));
app.serve();
51 changes: 33 additions & 18 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
const { stat, open, readAll } = Deno;
import { ServerRequest, serve } from './std/http/server.ts';
const { listen, stat, open, readAll } = Deno;
import {
Deferred,
defer,
} from 'https://deno.land/x/[email protected]/util/deferred.ts';
import { decode } from 'https://deno.land/std/strings/mod.ts';
Server,
ServerRequest,
} from 'http://deno.land/[email protected]/http/server.ts';
import { Response, processResponse } from './response.ts';
import { ErrorCode, getErrorMessage } from './errors.ts';
import { Method, Handler, HandlerConfig } from './handler.ts';
Expand All @@ -22,19 +20,20 @@ export {
link,
unlink,
} from './handler.ts';
export { Response } from './response.ts';

type HandlerMap = Map<string, Map<string, Handler>>; // Map<method, Map<path, handler>>

export function app(...handlerConfigs: HandlerConfig[]): App {
const a = new App(defaultPort);
a.handle(...handlerConfigs);
a.register(...handlerConfigs);
a.serve();
return a;
}

export class App {
private handlerMap: HandlerMap = new Map();
private cancel: Deferred = defer();
private server: Server;

constructor(
public readonly port = defaultPort,
Expand Down Expand Up @@ -99,16 +98,19 @@ export class App {
Object.assign(params, parseURLSearchParams(search));
}
} else {
const rawContentType = req.headers.get('content-type') || "application/octet-stream";
const [contentType, ...typeParamsArray] = rawContentType.split(';').map(s => s.trim());
const rawContentType =
req.headers.get('content-type') || 'application/octet-stream';
const [contentType, ...typeParamsArray] = rawContentType
.split(';')
.map(s => s.trim());
const typeParams = typeParamsArray.reduce((params, curr) => {
const [key, value] = curr.split('=');
params[key] = value;
return params;
}, {});

const decoder = new TextDecoder(typeParams['charset'] || "utf-8"); // TODO: downcase `charset` key
const decodedBody = decoder.decode(await readAll(req.body)); // FIXME: this line is should be refactored using Deno.Reader
const decoder = new TextDecoder(typeParams['charset'] || 'utf-8'); // TODO: downcase `charset` key
const decodedBody = decoder.decode(await req.body());

switch (contentType) {
case 'application/x-www-form-urlencoded':
Expand Down Expand Up @@ -137,16 +139,28 @@ export class App {
return res;
}

public handle(...handlerConfigs: HandlerConfig[]) {
// Deprecated
public handle = (...args) => {
console.error('handle is deprecated. Please use register instead of this.');
this.register(...args);
};

public register(...handlerConfigs: HandlerConfig[]) {
for (const { path, method, handler } of handlerConfigs) {
this.handlerMap.get(method).set(path, handler);
}
}

public unregister(path: string, method: Method) {
this.handlerMap.get(method).delete(path);
}

public async serve() {
const addr = `0.0.0.0:${this.port}`;
const listener = listen('tcp', addr);
console.log(`listening on http://${addr}/`);
for await (const { req, res } of serve(addr, this.cancel)) {
this.server = new Server(listener);
for await (const req of this.server) {
const method = req.method as Method;
let r: Response;
if (!req.url) {
Expand All @@ -169,11 +183,12 @@ export class App {
}
r = [status, getErrorMessage(status)];
}
await res.respond(processResponse(r));
await req.respond(processResponse(r));
}
}

public close() {
this.cancel.resolve();
}
// TODO: implement close
// public close() {
// this.server.close();
// }
}
2 changes: 1 addition & 1 deletion response.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Reader = Deno.Reader;
import { encode } from 'https://deno.land/std/strings/mod.ts';
import { encode } from 'https://deno.land/std@v0.11.0/strings/mod.ts';

// HeaderMap is a type of response headers.
type HeaderMap =
Expand Down
24 changes: 10 additions & 14 deletions serve_test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { test, runTests } from 'https://deno.land/std/testing/mod.ts';
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts';
import { test, runTests } from 'https://deno.land/std@v0.11.0/testing/mod.ts';
import { assertEquals } from 'https://deno.land/std@v0.11.0/testing/asserts.ts';
import { App, get, post } from './mod.ts';
import { HandlerConfig, Method } from './handler.ts';
const { exit } = Deno;
Expand Down Expand Up @@ -55,7 +55,7 @@ const testCases: Array<testCase> = [
path: 'params',
params: JSON.stringify({ name: 'ben' }),
method: Method.POST,
expected: 'ben'
expected: 'ben',
},
{
name: 'valid post with detailed content-type',
Expand All @@ -64,8 +64,8 @@ const testCases: Array<testCase> = [
params: JSON.stringify({ name: 'tom' }),
headers: { 'content-type': 'application/json; charset=utf-8' },
method: Method.POST,
expected: 'tom'
}
expected: 'tom',
},
// this test doesn't pass because deno's fetch is broken.
// {
// name: 'valid post formdata',
Expand All @@ -81,18 +81,14 @@ const testCases: Array<testCase> = [
// },
];

function newApp(handler: HandlerConfig): App {
const app = new App(testPort);
app.handle(handler);
return app;
}
const app = new App(testPort);
app.serve();

for (const tc of testCases) {
test({
name: tc.name,
async fn() {
const app = newApp(tc.registered);
app.serve();
app.register(tc.registered);

const reqInit: RequestInit = { method: tc.method };
if (typeof tc.params === 'string') {
Expand All @@ -108,8 +104,8 @@ for (const tc of testCases) {
assertEquals(actual, tc.expected);
assertEquals(contentLength, tc.expected.length.toString());

app.close();
await sleep(100); // Workaround to avoid `AddrInUse`
const { path, method } = tc.registered;
app.unregister(path, method);
},
});
}
Expand Down
5 changes: 2 additions & 3 deletions static_test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { test, runTests } from 'https://deno.land/std/testing/mod.ts';
import { assertEquals } from 'https://deno.land/std/testing/asserts.ts';
import { test, runTests } from 'https://deno.land/std@v0.11.0/testing/mod.ts';
import { assertEquals } from 'https://deno.land/std@v0.11.0/testing/asserts.ts';
import { App } from './mod.ts';
const { exit } = Deno;

Expand Down Expand Up @@ -63,6 +63,5 @@ for (const tc of testCases) {

(async () => {
await runTests();
app.close();
exit(0);
})();
79 changes: 0 additions & 79 deletions std/http/readers.ts

This file was deleted.

Loading

0 comments on commit 90b7b7d

Please sign in to comment.