Shared Flashcard Set

Details

Koa.js
koa.js
85
Computer Science
Professional
04/13/2021

Additional Computer Science Flashcards

 


 

Cards

Term
app.listen(...)
Definition

f(8000, () => {

  console.log("started app on " + 8000);
});
Term
app.callback()
Definition
Return a callback function suitable for the http.createServer() method to handle a request. You may also use this callback function to mount your Koa app in a Connect/Express app.
Term
app.use(function)
Definition
Add the given middleware function to this application.
Term
app.keys=
Definition

Set signed cookie keys.

These are passed to KeyGrip, however you may also pass your own KeyGrip instance. For example the following are acceptable:

f = ['im a newer secret', 'i like turtle'];
f = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');

These keys may be rotated and are used when signing cookies with the { signed: true } option:

ctx.cookies.set('name', 'tobi', { signed: true });
Term
app.context
Definition

the prototype from which ctx is created. You may add additional properties to ctx by editing this. This is useful for adding properties or methods to ctx to be used across your entire app, which may be more performant (no middleware) and/or easier (fewer require()s) at the expense of relying more on ctx, which could be considered an anti-pattern.

For example, to add a reference to your database from ctx:

f.db = db();

app.use(async ctx => {
  console.log(ctx.db);
});

 

Term
error handling
Definition

By default outputs all errors to stderr unless app.silent is true. The default error handler also won't output errors when err.status is 404 or err.expose is true. To perform custom error-handling logic such as centralized logging you can add an "error" event listener:

app.on('error', err => {
  log.error('server error', err)
});

If an error is in the req/res cycle and it is not possible to respond to the client, the Context instance is also passed:

app.on('error', (err, ctx) => {
  log.error('server error', err, ctx)
});

When an error occurs and it is still possible to respond to the client, aka no data has been written to the socket, Koa will respond appropriately with a 500 "Internal Server Error". In either case an app-level "error" is emitted for logging purposes.

Term
ctx.req
Definition
Node's request object.
Term
ctx.res
Definition

Node's response object.

Bypassing Koa's response handling is not supported. Avoid using the following node properties:

  • res.statusCode
  • res.writeHead()
  • res.write()
  • res.end()
Term
ctx.request
Definition
A Koa Request object.
Term
ctx.response
Definition
A Koa Response object.
Term
ctx.state
Definition

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

f.user = await User.find(id);

 

Term
ctx.app
Definition
Application instance reference.
Term
ctx.cookies.get(name, [options])
Definition

Get cookie name with options:

  • signed the cookie requested should be signed

Koa uses the cookies module where options are simply passed.

Term
ctx.cookies.set(name, value, [options])
Definition

Set cookie name to value with options:

  • maxAge a number representing the milliseconds from Date.now() for expiry
  • signed sign the cookie value
  • expires a Date for cookie expiration
  • path cookie path, /' by default
  • domain cookie domain
  • secure secure cookie
  • httpOnly server-accessible cookie, true by default
  • overwrite a boolean indicating whether to overwrite previously set cookies of the same name (false by default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.

Koa uses the cookies module where options are simply passed.

Term
ctx.throw([status], [msg], [properties])
Definition

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:

f(400);
f(400, 'name required');
f(400, 'name required', { user: user });

For example f(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.

f(401, 'access_denied', { user: user });

Koa uses http-errors to create errors.

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

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

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

Koa uses http-assert for assertions.

 

Term
ctx.respond
Definition

To bypass Koa's built-in response handling, you may explicitly set f = 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.

Term
request.header(s)
Definition
Request header object
Term
request.header(s)=
Definition
Set request header object.
Term
request.method
Definition
Request method.
Term
request.method=
Definition

Set request method, useful for implementing middleware such as methodOverride().

 

Term
request.length
Definition

Return request Content-Length as a number when present, or undefined.

 

Term
request.url
Definition
Get request URL.
Term
request.url=
Definition
Set request URL, useful for url rewrites.
Term
request.originalUrl
Definition
Get request original URL.
Term
request.origin
Definition

Get origin of URL, include protocol and host.

ctx.f
// => http://example.com

 

Term
request.href
Definition

Get full request URL, include protocolhost and url.

ctx.f;
// => http://example.com/foo/bar?q=1

 

Term
request.path
Definition
Get request pathname.
Term
request.path=
Definition
Set request pathname and retain query-string when present.
Term
request.querystring
Definition

Get raw query string void of ?.

Term
request.querystring=
Definition
Set raw query string.
Term
request.search
Definition

Get raw query string with the ?.

Term
request.search=
Definition
Set raw query string
Term
request.host
Definition
Get host (hostname:port) when present. Supports X-Forwarded-Host when app.proxy is true, otherwise Host is used.
Term
request.hostname
Definition

Get hostname when present. Supports X-Forwarded-Host when app.proxy is true, otherwise Host is used.

If host is IPv6, Koa delegates parsing to WHATWG URL API, Note This may impact performance.

Term
request.URL
Definition

Get WHATWG parsed URL object.

Term
request.type
Definition

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

const ct = ctx.f;
// => "image/png"
Term
request.charset
Definition

Get request charset when present, or undefined:

ctx.f;
// => "utf-8"
Term
request.query
Definition

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'
}
Term
request.query=
Definition

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

ctx.query = { next: '/login' };
Term
request.fresh
Definition

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');

// cache is ok
if (ctx.f) {
  ctx.status = 304;
  return;
}

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

Inverse of request.fresh.

Term
request.protocol
Definition
Return request protocol, "https" or "http". Supports X-Forwarded-Proto when app.proxy is true.
Term
request.secure
Definition
Shorthand for ctx.protocol == "https" to check if a request was issued via TLS.
Term
request.ip
Definition

Request remote address. Supports X-Forwarded-For when app.proxy is true.

 

Term
request.ips
Definition
When X-Forwarded-For is present and app.proxy is enabled an array of these ips is returned, ordered from upstream -> downstream. When disabled an empty array is returned.
Term
request.subdomains
Definition

Return subdomains as an array.

Subdomains are the dot-separated parts of the host before the main domain of the app. By default, the domain of the app is assumed to be the last two parts of the host. This can be changed by setting app.subdomainOffset.

For example, if the domain is "tobi.ferrets.example.com": If app.subdomainOffset is not set, ctx.subdomains is ["ferrets", "tobi"]. If app.subdomainOffset is 3, ctx.subdomains is ["tobi"].

Term
request.is(types...)
Definition

Check if the incoming request contains the "Content-Type" header field, and it contains any of the give mime 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'

// 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 only images are sent to a given route:

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:

  • request.accepts(types)
  • request.acceptsEncodings(types)
  • request.acceptsCharsets(charsets)
  • request.acceptsLanguages(langs)

If no types are supplied, all acceptable types are returned.

If multiple types are supplied, the best match will be returned. If no matches are found, a false is returned, and you should send a 406 "Not Acceptable" response to the client.

In the case of missing accept headers where any type is acceptable, the first type will be returned. Thus, the order of types you supply is important.

 

Term
request.accepts(types)
Definition

Check if the given type(s) is acceptable, returning the best match when true, otherwise false. The type value may be one or more mime type string such as "application/json", the extension name such as "json", or an array ["json", "html", "text/plain"].

// Accept: text/html
ctx.accepts('html');
// => "html"

// Accept: text/*, application/json
ctx.accepts('html');
// => "html"
ctx.accepts('text/html');
// => "text/html"
ctx.accepts('json', 'text');
// => "json"
ctx.accepts('application/json');
// => "application/json"

// Accept: text/*, application/json
ctx.accepts('image/png');
ctx.accepts('png');
// => false

// Accept: text/*;q=.5, application/json
ctx.accepts(['html', 'json']);
ctx.accepts('html', 'json');
// => "json"

// No Accept header
ctx.accepts('html', 'json');
// => "html"
ctx.accepts('json', 'html');
// => "json"

You may call ctx.accepts() as many times as you like, or use a switch:

switch (ctx.accepts('json', 'html', 'text')) {
  case 'json': break;
  case 'html': break;
  case 'text': break;
  default: ctx.throw(406, 'json, html, or text only');
}
Term
request.acceptsEncodings(encodings)
Definition

Check if encodings are acceptable, returning the best match when true, otherwise false. Note that you should include identity as one of the encodings!

// Accept-Encoding: gzip
ctx.acceptsEncodings('gzip', 'deflate', 'identity');
// => "gzip"

ctx.acceptsEncodings(['gzip', 'deflate', 'identity']);
// => "gzip"

When no arguments are given all accepted encodings are returned as an array:

// Accept-Encoding: gzip, deflate
ctx.acceptsEncodings();
// => ["gzip", "deflate", "identity"]

Note that the identity encoding (which means no encoding) could be unacceptable if the client explicitly sends identity;q=0. Although this is an edge case, you should still handle the case where this method returns false.

Term
request.acceptsCharsets(charsets)
Definition

Check if charsets are acceptable, returning the best match when true, otherwise false.

// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets('utf-8', 'utf-7');
// => "utf-8"

ctx.acceptsCharsets(['utf-7', 'utf-8']);
// => "utf-8"

When no arguments are given all accepted charsets are returned as an array:

// Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5
ctx.acceptsCharsets();
// => ["utf-8", "utf-7", "iso-8859-1"]

 

Term
request.acceptsLanguages(langs)
Definition

Check if langs are acceptable, returning the best match when true, otherwise false.

// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages('es', 'en');
// => "es"

ctx.acceptsLanguages(['en', 'es']);
// => "es"

When no arguments are given all accepted languages are returned as an array:

// Accept-Language: en;q=0.8, es, pt
ctx.acceptsLanguages();
// => ["es", "pt", "en"]

 

Term
request.idempotent
Definition
Check if the request is idempotent.
Term
request.socket
Definition
Return the request socket.
Term
request.get(field)
Definition
Return request header.
Term

Response header object.

Definition

Response header object.

Term
response.socket
Definition
Request socket.
Term
response.status
Definition
Get response status. By default, response.status is set to 404 unlike node's res.statusCode which defaults to 200.
Term
response.status=
Definition

Set response status via numeric code:

100 "continue", 101 "switching protocols", 102 "processing", 200 "ok", 201 "created", 202 "accepted", 203 "non-authoritative information", 204 "no content", 205 "reset content", 206 "partial content", 207 "multi-status", 208 "already reported", 226 "im used", 300 "multiple choices", 301 "moved permanently", 302 "found", 303 "see other", 304 "not modified", 305 "use proxy", 307 "temporary redirect", 308 "permanent redirect", 400 "bad request", 401 "unauthorized", 402 "payment required", 403 "forbidden", 404 "not found", 405 "method not allowed", 406 "not acceptable", 407 "proxy authentication required", 408 "request timeout", 409 "conflict", 410 "gone", 411 "length required", 412 "precondition failed", 413 "payload too large", 414 "uri too long", 415 "unsupported media type", 416 "range not satisfiable", 417 "expectation failed", 418 "I'm a teapot", 422 "unprocessable entity", 423 "locked", 424 "failed dependency", 426 "upgrade required", 428 "precondition required", 429 "too many requests", 431 "request header fields too large", 500 "internal server error", 501 "not implemented", 502 "bad gateway", 503 "service unavailable", 504 "gateway timeout", 505 "http version not supported", 506 "variant also negotiates", 507 "insufficient storage", 508 "loop detected", 510 "not extended", 511 "network authentication required"

Term
response.message
Definition
Get response status message. By default, it is associated with response.status.
Term
response.message=
Definition

Set response status message to the given value.

Term
response.length=
Definition

Set response Content-Length to the given value.

Term
response.length
Definition

Return response Content-Length as a number when present, or deduce from ctx.body when possible, or undefined.

 

Term
response.body
Definition

Get response body.

 

Term
response.body=
Definition

Set response body to one of the following:

  • string written
  • Buffer written
  • Stream piped
  • Object || Array json-stringified
  • null no content response

If response.status has not been set, Koa will automatically set the status to 200 or 204.

Term
String
Definition

The Content-Type is defaulted to text/html or text/plain, both with a default charset of utf-8. The Content-Length field is also set.

 

Term
Buffer
Definition

The Content-Type is defaulted to application/octet-stream, and Content-Length is also set.

 

Term
Stream
Definition

The Content-Type is defaulted to application/octet-stream.

Whenever a stream is set as the response body, .onerror is automatically added as a listener to the error event to catch any errors. In addition, whenever the request is closed (even prematurely), the stream is destroyed. If you do not want these two features, do not set the stream as the body directly. For example, you may not want this when setting the body as an HTTP stream in a proxy as it would destroy the underlying connection.

See: https://github.com/koajs/koa/pull/612 for more information.

Here's an example of stream error handling without automatically destroying the stream:

const PassThrough = require('stream').PassThrough;

app.use(async ctx => {
  ctx.body = someHTTPStream.on('error', ctx.onerror).pipe(PassThrough());
});
Term
Object
Definition

The Content-Type is defaulted to application/json. This includes plain objects { foo: 'bar' } and arrays ['foo', 'bar'].

 

Term
response.get(field)
Definition

Get a response header field value with case-insensitive field.

const etag = ctx.response.get('ETag');
Term
response.set(field, value)
Definition

Set response header field to value:

ctx.set('Cache-Control', 'no-cache');
Term
response.append(field, value)
Definition

Append additional header field with value val.

ctx.append('Link', '<http://127.0.0.1/>');
Term
response.set(fields)
Definition

Set several response header fields with an object:

ctx.set({
  'Etag': '1234',
  'Last-Modified': date
});
Term
response.remove(field)
Definition

Remove header field.

Term
response.type
Definition

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

const ct = ctx.type;
// => "image/png"
Term
response.type=
Definition

Set response Content-Type via mime string or file extension.

ctx.type = 'text/plain; charset=utf-8';
ctx.type = 'image/png';
ctx.type = '.png';
ctx.type = 'png';

Note: when appropriate a charset is selected for you, for example response.type = 'html' will default to "utf-8". If you need to overwrite charset, use ctx.set('Content-Type', 'text/html') to set response header field to value directly.

Term
response.is(types...)
Definition

Very similar to ctx.request.is(). Check whether the response type is one of the supplied types. This is particularly useful for creating middleware that manipulate responses.

For example, this is a middleware that minifies all HTML responses except for streams.

const minify = require('html-minifier');

app.use(async (ctx, next) => {
  await next();

  if (!ctx.response.is('html')) return;

  let body = ctx.body;
  if (!body || body.pipe) return;

  if (Buffer.isBuffer(body)) body = body.toString();
  ctx.body = minify(body);
});
Term
response.redirect(url, [alt])
Definition

Perform a [302] redirect to url.

The string "back" is special-cased to provide Referrer support, when Referrer is not present alt or "/" is used.

ctx.redirect('back');
ctx.redirect('back', '/index.html');
ctx.redirect('/login');
ctx.redirect('http://google.com');

To alter the default status of 302, simply assign the status before or after this call. To alter the body, assign it after this call:

ctx.status = 301;
ctx.redirect('/cart');
ctx.body = 'Redirecting to shopping cart';
Term
response.attachment([filename])
Definition

Set Content-Disposition to "attachment" to signal the client to prompt for download. Optionally specify the filename of the download.

 

Term
response.headerSent
Definition

Check if a response header has already been sent. Useful for seeing if the client may be notified on error.

 

Term
response.lastModified
Definition

Return the Last-Modified header as a Date, if it exists.

 

Term
response.lastModified=
Definition

Set the Last-Modified header as an appropriate UTC string. You can either set it as a Date or date string.

ctx.response.lastModified = new Date();
Term
response.etag=
Definition

Set the ETag of a response including the wrapped "s. Note that there is no corresponding response.etag getter.

ctx.response.etag = crypto.createHash('md5').update(ctx.body).digest('hex');
Term
response.vary(field)
Definition
Vary on field.
Term
response.flushHeaders()
Definition
Flush any set headers, and begin the body.
Supporting users have an ad free experience!