diff --git a/Makefile b/Makefile index a1b55ea..7601143 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ DOCS = public/index.md \ public/guide.md index.html: views/index.jade $(DOCS) - @./node_modules/.bin/jade $< -o . + @./node_modules/.bin/pug --obj pug-options.js $< -o . public/index.md: curl -s $(RAW)/koajs/koa/master/docs/api/index.md \ diff --git a/index.html b/index.html index 97f609d..33d5ae6 100644 --- a/index.html +++ b/index.html @@ -1,6 +1,6 @@ Koa - next generation web framework for node.js
next generation web framework for node.js

Introduction

Koa is a new web framework designed by the team behind Express, +window.analytics.page();

next generation web framework for node.js

Introduction

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any @@ -9,25 +9,19 @@

Installation

Koa requires node v7.6.0 or higher for ES2015 and async function support.

You can quickly install a supported version of node with your favorite version manager:

-
$ nvm install 7
+
$ nvm install 7
 $ npm i koa
-$ node my-koa-app.js
-
-

Async Functions with Babel

+$ node my-koa-app.js

Async Functions with Babel

To use async functions in Koa in versions of node < 7.6, we recommend using babel's require hook.

-
require('babel-register');
-// require the rest of the app that needs to be transpiled after the hook
-const app = require('./app');
-
-

To parse and transpile async functions, +

require('babel-register');
+// require the rest of the app that needs to be transpiled after the hook
+const app = require('./app');

To parse and transpile async functions, you should at a minimum have the transform-async-to-generator or transform-async-to-module-method plugins. For example, in your .babelrc file, you should have:

-
{
-  "plugins": ["transform-async-to-generator"]
-}
-
-

You can also use the env preset with a target option "node": "current" instead.

+
{
+  "plugins": ["transform-async-to-generator"]
+}

You can also use the env preset with a target option "node": "current" instead.

Application

A Koa application is an object containing an array of middleware functions which are composed and executed in a stack-like manner upon request. Koa is similar to many @@ -39,16 +33,34 @@

Application

among others. Despite supplying a reasonably large number of helpful methods Koa maintains a small footprint, as no middleware are bundled.

The obligatory hello world application:

-
const Koa = require('koa');
-const app = new Koa();
+
+
const Koa = require('koa');
+const app = new Koa();
 
-app.use(async ctx => {
-  ctx.body = 'Hello World';
+app.use(async ctx => {
+  ctx.body = 'Hello World';
 });
 
-app.listen(3000);
-
-

Cascading

+app.listen(3000);

Cascading

Koa middleware cascade in a more traditional way as you may be used to with similar tools - this was previously difficult to make user friendly with node's use of callbacks. However with async functions we can achieve "true" middleware. Contrasting Connect's implementation which @@ -60,35 +72,53 @@

Cascading

the function suspends and passes control to the next middleware defined. After there are no more middleware to execute downstream, the stack will unwind and each middleware is resumed to perform its upstream behaviour.

-
const Koa = require('koa');
-const app = new Koa();
+
+
const Koa = require('koa');
+const app = new Koa();
 
-// logger
+// logger
 
-app.use(async (ctx, next) => {
-  await next();
-  const rt = ctx.response.get('X-Response-Time');
-  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
+app.use(async (ctx, next) => {
+  await next();
+  const rt = ctx.response.get('X-Response-Time');
+  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
 });
 
-// x-response-time
+// x-response-time
 
-app.use(async (ctx, next) => {
-  const start = Date.now();
-  await next();
-  const ms = Date.now() - start;
-  ctx.set('X-Response-Time', `${ms}ms`);
+app.use(async (ctx, next) => {
+  const start = Date.now();
+  await next();
+  const ms = Date.now() - start;
+  ctx.set('X-Response-Time', `${ms}ms`);
 });
 
-// response
+// response
 
-app.use(async ctx => {
-  ctx.body = 'Hello World';
+app.use(async ctx => {
+  ctx.body = 'Hello World';
 });
 
-app.listen(3000);
-
-

Settings

+app.listen(3000);

Settings

Application settings are properties on the app instance, currently the following are supported:

Context

@@ -185,13 +199,11 @@

Error Handling

A Context is created per request, and is referenced in middleware as the receiver, or the ctx identifier, as shown in the following snippet:

-
app.use(async ctx => {
-  ctx; // is the Context
-  ctx.request; // is a Koa Request
-  ctx.response; // is a Koa Response
-});
-
-

Many of the context's accessors and methods simply delegate to their ctx.request or ctx.response +

app.use(async ctx => {
+  ctx; // is the Context
+  ctx.request; // is a Koa Request
+  ctx.response; // is a Koa Response
+});

Many of the context's accessors and methods simply delegate to their ctx.request or ctx.response equivalents for convenience, and are otherwise identical. For example ctx.type and ctx.length delegate to the response object, and ctx.path and ctx.method delegate to the request.

API

@@ -213,9 +225,7 @@

ctx.response

A Koa Response object.

ctx.state

The recommended namespace for passing information through middleware and to your frontend views.

-
ctx.state.user = await User.find(id);
-
-

ctx.app

+
ctx.state.user = await User.find(id);

ctx.app

Application instance reference.

ctx.cookies.get(name, [options])

Get cookie name with options:

@@ -240,32 +250,24 @@

ctx.throw([status], [msg], [properties

Helper method to throw an error with a .status property defaulting to 500 that will allow Koa to respond appropriately. The following combinations are allowed:

-
ctx.throw(400);
-ctx.throw(400, 'name required');
-ctx.throw(400, 'name required', { user: user });
-
-

For example ctx.throw(400, 'name required') is equivalent to:

-
const err = new Error('name required');
-err.status = 400;
-err.expose = true;
-throw err;
-
-

Note that these are user-level errors and are flagged with +

ctx.throw(400);
+ctx.throw(400, 'name required');
+ctx.throw(400, 'name required', { user: user });

For example ctx.throw(400, 'name required') is equivalent to:

+
const err = new Error('name required');
+err.status = 400;
+err.expose = true;
+throw err;

Note that these are user-level errors and are flagged with err.expose meaning the messages are appropriate for client responses, which is typically not the case for error messages since you do not want to leak failure details.

You may optionally pass a properties object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.

-
ctx.throw(401, 'access_denied', { user: user });
-
-

Koa uses http-errors to create errors.

+
ctx.throw(401, 'access_denied', { user: user });

Koa uses http-errors to create errors.

ctx.assert(value, [status], [msg], [properties])

Helper method to throw an error similar to .throw() when !value. Similar to node's assert() method.

-
ctx.assert(ctx.state.user, 401, 'User not found. Please login!');
-
-

Koa uses http-assert for assertions.

+
ctx.assert(ctx.state.user, 401, 'User not found. Please login!');

Koa uses http-assert for assertions.

ctx.respond

To bypass Koa's built-in response handling, you may explicitly set ctx.respond = false;. Use this if you want to write to the raw res object instead of letting Koa handle the response for you.

Note that using this is not supported by Koa. This may break intended functionality of Koa middleware and Koa itself. Using this property is considered a hack and is only a convenience to those wishing to use traditional fn(req, res) functions and middleware within Koa.

@@ -354,15 +356,11 @@

request.originalUrl

Get request original URL.

request.origin

Get origin of URL, include protocol and host.

-
ctx.request.origin
-// => http://example.com
-
-

request.href

+
ctx.request.origin
+// => http://example.com

request.href

Get full request URL, include protocol, host and url.

-
ctx.request.href;
-// => http://example.com/foo/bar?q=1
-
-

request.path

+
ctx.request.href;
+// => http://example.com/foo/bar?q=1

request.path

Get request pathname.

request.path=

Set request pathname and retain query-string when present.

@@ -387,47 +385,37 @@

request.URL

Get WHATWG parsed URL object.

request.type

Get request Content-Type void of parameters such as "charset".

-
const ct = ctx.request.type;
-// => "image/png"
-
-

request.charset

+
const ct = ctx.request.type;
+// => "image/png"

request.charset

Get request charset when present, or undefined:

-
ctx.request.charset;
-// => "utf-8"
-
-

request.query

+
ctx.request.charset;
+// => "utf-8"

request.query

Get parsed query-string, returning an empty object when no query-string is present. Note that this getter does not support nested parsing.

For example "color=blue&size=small":

-
{
-  color: 'blue',
-  size: 'small'
-}
-
-

request.query=

+
{
+  color: 'blue',
+  size: 'small'
+}

request.query=

Set query-string to the given object. Note that this setter does not support nested objects.

-
ctx.query = { next: '/login' };
-
-

request.fresh

+
ctx.query = { next: '/login' };

request.fresh

Check if a request cache is "fresh", aka the contents have not changed. This method is for cache negotiation between If-None-Match / ETag, and If-Modified-Since and Last-Modified. It should be referenced after setting one or more of these response headers.

-
// freshness check requires status 20x or 304
-ctx.status = 200;
-ctx.set('ETag', '123');
+
// freshness check requires status 20x or 304
+ctx.status = 200;
+ctx.set('ETag', '123');
 
-// cache is ok
-if (ctx.fresh) {
-  ctx.status = 304;
-  return;
+// cache is ok
+if (ctx.fresh) {
+  ctx.status = 304;
+  return;
 }
 
-// cache is stale
-// fetch new data
-ctx.body = await db.find('something');
-
-

request.stale

+// cache is stale +// fetch new data +ctx.body = await db.find('something');

request.stale

Inverse of request.fresh.

request.protocol

Return request protocol, "https" or "http". Supports X-Forwarded-Proto @@ -456,27 +444,23 @@

request.is(types...)

If there is no request body, null is returned. If there is no content type, or the match fails false is returned. Otherwise, it returns the matching content-type.

-
// With Content-Type: text/html; charset=utf-8
-ctx.is('html'); // => 'html'
-ctx.is('text/html'); // => 'text/html'
-ctx.is('text/*', 'text/html'); // => 'text/html'
+
// With Content-Type: text/html; charset=utf-8
+ctx.is('html'); // => 'html'
+ctx.is('text/html'); // => 'text/html'
+ctx.is('text/*', 'text/html'); // => 'text/html'
 
-// When Content-Type is application/json
-ctx.is('json', 'urlencoded'); // => 'json'
-ctx.is('application/json'); // => 'application/json'
-ctx.is('html', 'application/*'); // => 'application/json'
+// When Content-Type is application/json
+ctx.is('json', 'urlencoded'); // => 'json'
+ctx.is('application/json'); // => 'application/json'
+ctx.is('html', 'application/*'); // => 'application/json'
 
-ctx.is('html'); // => false
-
-

For example if you want to ensure that +ctx.is('html'); // => false

For example if you want to ensure that only images are sent to a given route:

-
if (ctx.is('image/*')) {
-  // process
-} else {
-  ctx.throw(415, 'images only!');
-}
-
-

Content Negotiation

+
if (ctx.is('image/*')) {
+  // process
+} else {
+  ctx.throw(415, 'images only!');
+}

Content Negotiation

Koa's request object includes helpful content negotiation utilities powered by accepts and negotiator. These utilities are:

Jobs

Looking for work with an amazing tech company? Check out these positions.

Links

Community links to discover third-party middleware for Koa, full runnable examples, thorough guides and more! If you have questions join us in IRC! -

\ No newline at end of file +

\ No newline at end of file diff --git a/package.json b/package.json index 95902a5..f5308d5 100644 --- a/package.json +++ b/package.json @@ -4,8 +4,10 @@ "version": "0.0.1", "description": "the koa website", "dependencies": { - "jade": "~0.35.0", + "highlight.js": "^9.12.0", "marked": "~0.3.17", + "pug": "^2.0.0-rc.2", + "pug-cli": "^1.0.0-alpha6", "stdin": "0.0.1" } } diff --git a/pug-options.js b/pug-options.js new file mode 100644 index 0000000..a674905 --- /dev/null +++ b/pug-options.js @@ -0,0 +1,71 @@ +{ + filters: + { + markdown: function (text) + { + var marked = require("marked"); + var renderer = new marked.Renderer(); + var highlight = require('highlight.js').highlight; + var runkitRegExp = /^(.|\n)*$/; + var runkitContext = { options: '{}', activated: false }; + + renderer.code = function(code, lang, escaped) { + + if (!global.exampleCount) + global.exampleCount = 0; + + var out = highlight(lang, code).value || code; + var escaped = out !== code ? out : escapeCode(out, true); + var id = "example-" + (global.exampleCount++); + + var script = runkitContext.activated ? "" : ""; + + runkitContext.activated = false; + + return "
" + escaped + "
" + script; + }; + + renderer.html = function(text) { + var result = runkitRegExp.exec(text); + + if (!result) return text; + + runkitContext.activated = true; + + return text; + }; + + return marked(text, { renderer: renderer }); + + function endpoint(id, count) { + + if (!window.RunKit) + if (typeof count === "undefined" || count < 20) + return setTimeout(endpoint, 500, id, count || 0 + 1); + else + return; + + var parent = document.getElementById(id); + var source = parent.textContent; + + parent.innerHTML = ""; + + RunKit.createNotebook({ + element: parent, + nodeVersion: "8.x.x", + source: source, + mode: "endpoint" + }); + } + + function escapeCode(code) { + return code + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + } + } +} \ No newline at end of file diff --git a/views/index.jade b/views/index.jade index b0d6c77..9a51896 100644 --- a/views/index.jade +++ b/views/index.jade @@ -12,7 +12,7 @@ html window.analytics.load("9u0xff0b3k"); window.analytics.page(); script(src='stats.js') - script(src='https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.10.0/highlight.min.js') + script(src="https://embed.runkit.com", async, defer) body section#top #menu @@ -42,19 +42,19 @@ html section .content - include ../public/index.md + include:markdown ../public/index.md section .content - include ../public/context.md + include:markdown ../public/context.md section .content - include ../public/request.md + include:markdown ../public/request.md section .content - include ../public/response.md + include:markdown ../public/response.md section .content @@ -86,5 +86,4 @@ html li: a(href='https://github.com/koajs/koa/blob/master/docs/guide.md') Guide li: a(href='https://github.com/koajs/koa/blob/master/docs/faq.md') FAQ li: #koajs on freenode - script. - hljs.initHighlightingOnLoad(); +