Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface MidwayMockContext<ResponseBodyT>

deprecated

Type parameters

  • ResponseBodyT

Hierarchy

Indexable

[key: string]: any
deprecated

Properties

URL

URL: URL

Get WHATWG parsed URL object.

accept

accept: Accepts
see

Request#accept

acceptJSON

acceptJSON: boolean
see

Request#acceptJSON

app

assert

assert: typeof httpAssert

Similar to .throw(), adds assertion.

this.assert(this.user, 401, 'Please login!');

See: https://github.com/jshttp/http-assert

body

body: ResponseBodyT

cookies

cookies: EggCookies

curl

curl: EggHttpClient["request"]

http request helper base on httpclient, it will auto save httpclient log. Keep the same api with httpclient.request(url, args). See https://github.com/node-modules/urllib#api-doc for more details.

data

data: any

Set the ctx.body.data value

member

{Object} Context#data=

example
ctx.data = {
  id: 1,
  name: 'fengmk2'
};

will get responce

HTTP/1.1 200 OK

{
  "data": {
    "id": 1,
    "name": "fengmk2"
  }
}

etag

etag: string

Get/Set the ETag of a response. This will normalize the quotes if necessary.

this.response.etag = 'md5hashsum';
this.response.etag = '"md5hashsum"';
this.response.etag = 'W/"123456789"';
param
api

public

fresh

fresh: boolean

Check if the request is fresh, aka Last-Modified and/or the ETag still match.

header

header: IncomingHttpHeaders

Return request header.

headerSent

headerSent: boolean

Check if a header has been written to the socket.

headers

headers: IncomingHttpHeaders

Return request header, alias as request.header

helper

helper: IHelper

host

host: string

Parse the "Host" header field host and support X-Forwarded-Host when a proxy is enabled.

hostname

hostname: string

Parse the "Host" header field hostname and support X-Forwarded-Host when a proxy is enabled.

href

href: string

Get full request URL.

httpclient

httpclient: EggContextHttpClient

idempotent

idempotent: boolean

Check if the request is idempotent.

ip

ip: string
see

Request#ip

ips

ips: string[]

When app.proxy is true, parse the "X-Forwarded-For" ip address list.

For example if the value were "client, proxy1, proxy2" you would receive the array ["client", "proxy1", "proxy2"] where "proxy2" is the furthest down-stream.

lastModified

lastModified: Date

Get the Last-Modified date in Date form, if it exists. Set the Last-Modified date using a string or a Date.

this.response.lastModified = new Date();
this.response.lastModified = '2013-09-13';

length

length: number

Return parsed response Content-Length when present. Set Content-Length field to n.

locals

locals: IApplicationLocals & IContextLocals

locals is an object for view, you can use app.locals and ctx.locals to set variables, which will be used as data when view is rendering. The difference between app.locals and ctx.locals is the context level, app.locals is global level, and ctx.locals is request level. when you get ctx.locals, it will merge app.locals.

when you set locals, only object is available

this.locals = {
  a: 1
};
this.locals = {
  b: 1
};
this.locals.c = 1;
console.log(this.locals);
{
  a: 1,
  b: 1,
  c: 1,
};

ctx.locals has cache, it only merges app.locals once in one request.

member

{Object} Context#locals

logger

logger: EggLogger

Logger for Application, wrapping app.coreLogger with context infomation

member

{ContextLogger} Context#logger

since

1.0.0

example
this.logger.info('some request data: %j', this.request.body);
this.logger.warn('WARNING!!!!');

message

message: string

Get response status message

meta

meta: any

set ctx.body.meta value

example
ctx.meta = {
  count: 100
};

will get responce

HTTP/1.1 200 OK

{
  "meta": {
    "count": 100
  }
}

method

method: string

Get/Set request method.

origin

origin: string

Get origin of URL.

originalUrl

originalUrl: string

params

params: any

Resource Parameters

example
ctx.params.id {string}

GET /api/users/1 => '1'

ctx.params.ids {Array}

GET /api/users/1,2,3 => ['1', '2', '3']

ctx.params.fields {Array}

Expect request return data fields, for example GET /api/users/1?fields=name,title => ['name', 'title'].

ctx.params.data {Object}

Tht request data object

ctx.params.page {Number}

Page number, GET /api/users?page=10 => 10

ctx.params.per_page {Number}

The number of every page, GET /api/users?per_page=20 => 20

path

path: string

Get request pathname. Set pathname, retaining the query-string when present.

protocol

protocol: string

Return the protocol string "http" or "https" when requested with TLS. When the proxy setting is enabled the "X-Forwarded-Proto" header field will be trusted. If you're running behind a reverse proxy that supplies https for you this may be enabled.

queries

queries: PlainObject<string[]>
see

Request#queries

query

query: PlainObject<string>
see

Request#query

querystring

querystring: string

Get/Set query string.

realStatus

realStatus: number
see

Response#realStatus

req

req: IncomingMessage

request

request: Request

requestContext

requestContext: IMidwayContainer

res

res: ServerResponse

Optional respond

respond: boolean

response

response: Response<ResponseBodyT>

search

search: string

Get the search string. Same as the querystring except it includes the leading ?.

Set the search string. Same as response.querystring= but included for ubiquity.

secure

secure: boolean

Short-hand for:

this.protocol == 'https'

service

service: IService

socket

socket: Socket

Return the request socket.

stale

stale: boolean

Check if the request is stale, aka "Last-Modified" and / or the "ETag" for the resource has changed.

startTime

startTime: number

starttime

starttime: number

Request start time

state

state: any

alias to locals, compatible with koa that use this variable

status

status: number

Get/Set response status code.

subdomains

subdomains: string[]

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, this.subdomains is ["ferrets", "tobi"]. If app.subdomainOffset is 3, this.subdomains is ["tobi"].

type

type: string

Return the response mime type void of parameters such as "charset".

Set Content-Type response header with type through mime.lookup() when it does not contain a charset.

Examples:

this.type = '.html';
this.type = 'html';
this.type = 'json';
this.type = 'application/json';
this.type = 'png';

url

url: string

Get/Set request URL.

view

view: ContextView

View instance that is created every request

writable

writable: boolean

Checks if the request is writable. Tests for the existence of the socket as node sometimes does not set it.

Methods

__

  • __(key: string, ...values: string[]): string

accepts

  • accepts(): string[]
  • accepts(...types: string[]): string | false
  • accepts(types: string[]): string | false
  • Check if the given type(s) is acceptable, returning the best match when true, otherwise false, in which case you should respond with 406 "Not Acceptable".

    The type value may be a single mime type string such as "application/json", the extension name such as "json" or an array ["json", "html", "text/plain"]. When a list or array is given the best match, if any is returned.

    Examples:

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

    Returns string[]

  • Parameters

    • Rest ...types: string[]

    Returns string | false

  • Parameters

    • types: string[]

    Returns string | false

acceptsCharsets

  • acceptsCharsets(): string[]
  • acceptsCharsets(...charsets: string[]): string | false
  • acceptsCharsets(charsets: string[]): string | false

acceptsEncodings

  • acceptsEncodings(): string[]
  • acceptsEncodings(...encodings: string[]): string | false
  • acceptsEncodings(encodings: string[]): string | false

acceptsLanguages

  • acceptsLanguages(): string[]
  • acceptsLanguages(...langs: string[]): string | false
  • acceptsLanguages(langs: string[]): string | false

append

  • append(field: string, val: string | string[]): void
  • Append additional header field with value val.

    Examples:

    this.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
    this.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
    this.append('Warning', '199 Miscellaneous warning');
    

    Parameters

    • field: string
    • val: string | string[]

    Returns void

attachment

  • attachment(filename?: string, options?: Options): void

cleanupRequestFiles

  • cleanupRequestFiles(files?: EggFile[]): Promise<void>

flushHeaders

  • flushHeaders(): void

get

  • get(field: string): string
  • Return request header. If the header is not set, will return an empty string.

    The Referrer header field is special-cased, both Referrer and Referer are interchangeable.

    Examples:

    this.get('Content-Type');
    // => "text/plain"
    
    this.get('content-type');
    // => "text/plain"
    
    this.get('Something');
    // => ''
    

    Parameters

    • field: string

    Returns string

getFileStream

  • getFileStream(options?: MultipartOptions): Promise<MultipartFileStream>

getLogger

  • getLogger(name: string): EggLogger

gettext

  • gettext(key: string, ...values: string[]): string

inspect

  • inspect(): any

is

  • is(...types: string[]): string | false | null
  • is(types: string[]): string | false | null
  • 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, false is returned. Otherwise, it returns the first type that matches.

    Examples:

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

    Parameters

    • Rest ...types: string[]

    Returns string | false | null

  • Parameters

    • types: string[]

    Returns string | false | null

multipart

  • multipart(options?: MultipartOptions): function
  • create multipart.parts instance, to get separated files.

    Parameters

    • Optional options: MultipartOptions

    Returns function

    return a function which return a Promise

      • (fn?: Function): Promise<any>
      • Parameters

        • Optional fn: Function

        Returns Promise<any>

onerror

  • onerror(err: Error): void

redirect

  • redirect(url: string, alt?: string): void

remove

  • remove(field: string): void

render

  • render(name: string, locals?: any, options?: RenderOptions): Promise<null>
  • Render a file by view engine, then set to body

    Parameters

    • name: string

      the file path based on root

    • Optional locals: any
    • Optional options: RenderOptions

    Returns Promise<null>

    result - return a promise with a render result

renderString

  • renderString(name: string, locals?: any, options?: RenderOptions): Promise<string>

renderView

  • renderView(name: string, locals?: any, options?: RenderOptions): Promise<string>

saveRequestFiles

  • saveRequestFiles(): Promise<void>

set

  • set(field: object): void
  • set(field: string, val: string | string[]): void

throw

  • throw(message: string, code?: number, properties?: object): never
  • throw(status: number): never
  • throw(...properties: Array<number | string | object>): never

toJSON

  • toJSON(): any

vary

  • vary(field: string): void

Generated using TypeDoc