Commit ea03ea61 authored by Geovera's avatar Geovera

gitignore and change to database

parent 19f69801

Too many changes to show.

To preserve performance only 335 of 335+ files are displayed.

server/database/config.json
server/node_modules/
......@@ -240,7 +240,7 @@ function createMysqlDbUser()
SQL7="CREATE TABLE users(
id bigint unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
discord_id CHAR(30) NOT NULL,
discord_id int,
house_id bigint unsigned,
leadership smallint unsigned,
FOREIGN KEY(house_id) REFERENCES houses(id));"
......
{
"host": "localhost",
"user": "root",
"password": "goodyear",
"database": "conquerors_blade_db",
"connectionLimit": 100
}
\ No newline at end of file
......@@ -2,4 +2,8 @@ const db = require('../database/database');
const users = {};
users.getUser = async (context, next) => {
};
module.exports = users;
\ No newline at end of file
The MIT License (MIT)
Copyright (c) 2015 Alexander C. Mingoia
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# @koa/router
Router middleware for [koa](https://github.com/koajs/koa)
[![NPM version](https://img.shields.io/npm/v/@koa/router.svg?style=flat)](https://npmjs.org/package/@koa/router)
[![NPM Downloads](https://img.shields.io/npm/dm/@koa/router.svg?style=flat)](https://npmjs.org/package/@koa/router)
[![Node.js Version](https://img.shields.io/node/v/@koa/router.svg?style=flat)](http://nodejs.org/download/)
[![Build Status](https://img.shields.io/travis/koajs/router.svg?style=flat)](http://travis-ci.org/koajs/router)
[![gitter](https://img.shields.io/gitter/room/koajs/koa.svg?style=flat)](https://gitter.im/koajs/koa)
* Express-style routing (`app.get`, `app.put`, `app.post`, etc.)
* Named URL parameters
* Named routes with URL generation
* Responds to `OPTIONS` requests with allowed methods
* Support for `405 Method Not Allowed` and `501 Not Implemented`
* Multiple route middleware
* Multiple and nestable routers
* `async/await` support
## Migrating to 7 / Koa 2
- The API has changed to match the new promise-based middleware
signature of koa 2. See the
[koa 2.x readme](https://github.com/koajs/koa/tree/2.0.0-alpha.3) for more
information.
- Middleware is now always run in the order declared by `.use()` (or `.get()`,
etc.), which matches Express 4 API.
## Installation
Install using [npm](https://www.npmjs.org/):
```sh
npm install @koa/router
```
## [API Reference](./API.md)
## Contributing
Please submit all issues and pull requests to the [koajs/router](http://github.com/koajs/router) repository!
## Tests
Run tests using `npm test`.
## Support
If you have any problem or suggestion please open an issue [here](https://github.com/koajs/router/issues).
## Call for Maintainers
This module is forked from the original [koa-router](https://github.com/ZijianHe/koa-router) due to its lack of activity. `koa-router` is the most widely used router module in the Koa community and we need maintainers. If you're interested in fixing bugs or implementing new features feel free to open a pull request. We'll be adding active contributors as collaborators.
Thanks to the original authors @alexmingoia and the original team for their great work.
8.0.0 / 2019-06-16
==================
**others**
* [[`b5dd5e8`](http://github.com/koajs/koa-router/commit/b5dd5e8f00e841b7061a62ab6228cbe96a999470)] - chore: rename to @koa/router (dead-horse <<dead_horse@qq.com>>)
-------------
# Changelogs inherit from koa-router.
## 7.4.0
- Fix router.url() for multiple nested routers [#407](https://github.com/alexmingoia/koa-router/pull/407)
- `layer.name` added to `ctx` at `ctx.routerName` during routing [#412](https://github.com/alexmingoia/koa-router/pull/412)
- Router.use() was erroneously settings `(.*)` as a prefix to all routers nested with .use that did not pass an explicit prefix string as the first argument. This resulted in routes being matched that should not have been, included the running of multiple route handlers in error. [#369](https://github.com/alexmingoia/koa-router/issues/369) and [#410](https://github.com/alexmingoia/koa-router/issues/410) include information on this issue.
## 7.3.0
- Router#url() now accepts query parameters to add to generated urls [#396](https://github.com/alexmingoia/koa-router/pull/396)
## 7.2.1
- Respond to CORS preflights with 200, 0 length body [#359](https://github.com/alexmingoia/koa-router/issues/359)
## 7.2.0
- Fix a bug in Router#url and append Router object to ctx. [#350](https://github.com/alexmingoia/koa-router/pull/350)
- Adds `_matchedRouteName` to context [#337](https://github.com/alexmingoia/koa-router/pull/337)
- Respond to CORS preflights with 200, 0 length body [#359](https://github.com/alexmingoia/koa-router/issues/359)
## 7.1.1
- Fix bug where param handlers were run out of order [#282](https://github.com/alexmingoia/koa-router/pull/282)
## 7.1.0
- Backports: merge 5.4 work into the 7.x upstream. See 5.4.0 updates for more details.
## 7.0.1
- Fix: allowedMethods should be ctx.method not this.method [#215](https://github.com/alexmingoia/koa-router/pull/215)
## 7.0.0
- The API has changed to match the new promise-based middleware
signature of koa 2. See the
[koa 2.x readme](https://github.com/koajs/koa/tree/2.0.0-alpha.3) for more
information.
- Middleware is now always run in the order declared by `.use()` (or `.get()`,
etc.), which matches Express 4 API.
## 5.4.0
- Expose matched route at `ctx._matchedRoute`.
## 5.3.0
- Register multiple routes with array of paths [#203](https://github.com/alexmingoia/koa-router/issue/143).
- Improved router.url() [#143](https://github.com/alexmingoia/koa-router/pull/143)
- Adds support for named routes and regular expressions
[#152](https://github.com/alexmingoia/koa-router/pull/152)
- Add support for custom throw functions for 405 and 501 responses [#206](https://github.com/alexmingoia/koa-router/pull/206)
## 5.2.3
- Fix for middleware running twice when nesting routes [#184](https://github.com/alexmingoia/koa-router/issues/184)
## 5.2.2
- Register routes without params before those with params [#183](https://github.com/alexmingoia/koa-router/pull/183)
- Fix for allowed methods [#182](https://github.com/alexmingoia/koa-router/issues/182)
## 5.2.0
- Add support for async/await. Resolves [#130](https://github.com/alexmingoia/koa-router/issues/130).
- Add support for array of paths by Router#use(). Resolves [#175](https://github.com/alexmingoia/koa-router/issues/175).
- Inherit param middleware when nesting routers. Fixes [#170](https://github.com/alexmingoia/koa-router/issues/170).
- Default router middleware without path to root. Fixes [#161](https://github.com/alexmingoia/koa-router/issues/161), [#155](https://github.com/alexmingoia/koa-router/issues/155), [#156](https://github.com/alexmingoia/koa-router/issues/156).
- Run nested router middleware after parent's. Fixes [#156](https://github.com/alexmingoia/koa-router/issues/156).
- Remove dependency on koa-compose.
## 5.1.1
- Match routes in order they were defined. Fixes #131.
## 5.1.0
- Support mounting router middleware at a given path.
## 5.0.1
- Fix bug with missing parameters when nesting routers.
## 5.0.0
- Remove confusing API for extending koa app with router methods. Router#use()
does not have the same behavior as app#use().
- Add support for nesting routes.
- Remove support for regular expression routes to achieve nestable routers and
enable future trie-based routing optimizations.
## 4.3.2
- Do not send 405 if route matched but status is 404. Fixes #112, closes #114.
## 4.3.1
- Do not run middleware if not yielded to by previous middleware. Fixes #115.
## 4.3.0
- Add support for router prefixes.
- Add MIT license.
## 4.2.0
- Fixed issue with router middleware being applied even if no route was
matched.
- Router.url - new static method to generate url from url pattern and data
## 4.1.0
Private API changed to separate context parameter decoration from route
matching. `Router#match` and `Route#match` are now pure functions that return
an array of routes that match the URL path.
For modules using this private API that need to determine if a method and path
match a route, `route.methods` must be checked against the routes returned from
`router.match()`:
```javascript
var matchedRoute = router.match(path).filter(function (route) {
return ~route.methods.indexOf(method);
}).shift();
```
## 4.0.0
405, 501, and OPTIONS response handling was moved into separate middleware
`router.allowedMethods()`. This resolves incorrect 501 or 405 responses when
using multiple routers.
### Breaking changes
4.x is mostly backwards compatible with 3.x, except for the following:
- Instantiating a router with `new` and `app` returns the router instance,
whereas 3.x returns the router middleware. When creating a router in 4.x, the
only time router middleware is returned is when creating using the
`Router(app)` signature (with `app` and without `new`).
## API Reference
{{#module name="koa-router"~}}
{{>body~}}
{{>member-index~}}
{{>members~}}
{{/module~}}
var debug = require('debug')('koa-router');
var pathToRegExp = require('path-to-regexp');
var uri = require('urijs');
module.exports = Layer;
/**
* Initialize a new routing Layer with given `method`, `path`, and `middleware`.
*
* @param {String|RegExp} path Path string or regular expression.
* @param {Array} methods Array of HTTP verbs.
* @param {Array} middleware Layer callback/middleware or series of.
* @param {Object=} opts
* @param {String=} opts.name route name
* @param {String=} opts.sensitive case sensitive (default: false)
* @param {String=} opts.strict require the trailing slash (default: false)
* @returns {Layer}
* @private
*/
function Layer(path, methods, middleware, opts) {
this.opts = opts || {};
this.name = this.opts.name || null;
this.methods = [];
this.paramNames = [];
this.stack = Array.isArray(middleware) ? middleware : [middleware];
for(var i = 0; i < methods.length; i++) {
var l = this.methods.push(methods[i].toUpperCase());
if (this.methods[l-1] === 'GET') {
this.methods.unshift('HEAD');
}
}
// ensure middleware is a function
for (var i = 0; i < this.stack.length; i++) {
var fn = this.stack[i];
var type = (typeof fn);
if (type !== 'function') {
throw new Error(
methods.toString() + " `" + (this.opts.name || path) +"`: `middleware` "
+ "must be a function, not `" + type + "`"
);
}
}
this.path = path;
this.regexp = pathToRegExp(path, this.paramNames, this.opts);
debug('defined route %s %s', this.methods, this.opts.prefix + this.path);
};
/**
* Returns whether request `path` matches route.
*
* @param {String} path
* @returns {Boolean}
* @private
*/
Layer.prototype.match = function (path) {
return this.regexp.test(path);
};
/**
* Returns map of URL parameters for given `path` and `paramNames`.
*
* @param {String} path
* @param {Array.<String>} captures
* @param {Object=} existingParams
* @returns {Object}
* @private
*/
Layer.prototype.params = function (path, captures, existingParams) {
var params = existingParams || {};
for (var len = captures.length, i=0; i<len; i++) {
if (this.paramNames[i]) {
var c = captures[i];
params[this.paramNames[i].name] = c ? safeDecodeURIComponent(c) : c;
}
}
return params;
};
/**
* Returns array of regexp url path captures.
*
* @param {String} path
* @returns {Array.<String>}
* @private
*/
Layer.prototype.captures = function (path) {
if (this.opts.ignoreCaptures) return [];
return path.match(this.regexp).slice(1);
};
/**
* Generate URL for route using given `params`.
*
* @example
*
* ```javascript
* const route = new Layer('/users/:id', ['GET'], fn);
*
* route.url({ id: 123 }); // => "/users/123"
* ```
*
* @param {Object} params url parameters
* @returns {String}
* @private
*/
Layer.prototype.url = function (params, options) {
var args = params;
var url = this.path.replace(/\(\.\*\)/g, '');
var toPath = pathToRegExp.compile(url);
var replaced;
if (typeof params != 'object') {
args = Array.prototype.slice.call(arguments);
if (typeof args[args.length - 1] == 'object') {
options = args[args.length - 1];
args = args.slice(0, args.length - 1);
}
}
var tokens = pathToRegExp.parse(url);
var replace = {};
if (args instanceof Array) {
for (var len = tokens.length, i=0, j=0; i<len; i++) {
if (tokens[i].name) replace[tokens[i].name] = args[j++];
}
} else if (tokens.some(token => token.name)) {
replace = params;
} else {
options = params;
}
replaced = toPath(replace);
if (options && options.query) {
var replaced = new uri(replaced)
replaced.search(options.query);
return replaced.toString();
}
return replaced;
};
/**
* Run validations on route named parameters.
*
* @example
*
* ```javascript
* router
* .param('user', function (id, ctx, next) {
* ctx.user = users[id];
* if (!user) return ctx.status = 404;
* next();
* })
* .get('/users/:user', function (ctx, next) {
* ctx.body = ctx.user;
* });
* ```
*
* @param {String} param
* @param {Function} middleware
* @returns {Layer}
* @private
*/
Layer.prototype.param = function (param, fn) {
var stack = this.stack;
var params = this.paramNames;
var middleware = function (ctx, next) {
return fn.call(this, ctx.params[param], ctx, next);
};
middleware.param = param;
var names = params.map(function (p) {
return p.name;
});
var x = names.indexOf(param);
if (x > -1) {
// iterate through the stack, to figure out where to place the handler fn
stack.some(function (fn, i) {
// param handlers are always first, so when we find an fn w/o a param property, stop here
// if the param handler at this part of the stack comes after the one we are adding, stop here
if (!fn.param || names.indexOf(fn.param) > x) {
// inject this param handler right before the current item
stack.splice(i, 0, middleware);
return true; // then break the loop
}
});
}
return this;
};
/**
* Prefix route path.
*
* @param {String} prefix
* @returns {Layer}
* @private
*/
Layer.prototype.setPrefix = function (prefix) {
if (this.path) {
this.path = prefix + this.path;
this.paramNames = [];
this.regexp = pathToRegExp(this.path, this.paramNames, this.opts);
}
return this;
};
/**
* Safe decodeURIComponent, won't throw any error.
* If `decodeURIComponent` error happen, just return the original value.
*
* @param {String} text
* @returns {String} URL decode original string.
* @private
*/
function safeDecodeURIComponent(text) {
try {
return decodeURIComponent(text);
} catch (e) {
return text;
}
}
/**
* RESTful resource routing middleware for koa.
*
* @author Alex Mingoia <talk@alexmingoia.com>
* @link https://github.com/alexmingoia/koa-router
*/
var debug = require('debug')('koa-router');
var compose = require('koa-compose');
var HttpError = require('http-errors');
var methods = require('methods');
var Layer = require('./layer');
/**
* @module koa-router
*/
module.exports = Router;
/**
* Create a new router.
*
* @example
*
* Basic usage:
*
* ```javascript
* const Koa = require('koa');
* const Router = require('@koa/router');
*
* const app = new Koa();
* const router = new Router();
*
* router.get('/', (ctx, next) => {
* // ctx.router available
* });
*
* app
* .use(router.routes())
* .use(router.allowedMethods());
* ```
*
* @alias module:koa-router
* @param {Object=} opts
* @param {String=} opts.prefix prefix router paths
* @constructor
*/
function Router(opts) {
if (!(this instanceof Router)) {
return new Router(opts);
}
this.opts = opts || {};
this.methods = this.opts.methods || [
'HEAD',
'OPTIONS',
'GET',
'PUT',
'PATCH',
'POST',
'DELETE'
];
this.params = {};
this.stack = [];
};
/**
* Create `router.verb()` methods, where *verb* is one of the HTTP verbs such
* as `router.get()` or `router.post()`.
*
* Match URL patterns to callback functions or controller actions using `router.verb()`,
* where **verb** is one of the HTTP verbs such as `router.get()` or `router.post()`.
*
* Additionaly, `router.all()` can be used to match against all methods.
*
* ```javascript
* router
* .get('/', (ctx, next) => {
* ctx.body = 'Hello World!';
* })
* .post('/users', (ctx, next) => {
* // ...
* })
* .put('/users/:id', (ctx, next) => {
* // ...
* })
* .del('/users/:id', (ctx, next) => {
* // ...
* })
* .all('/users/:id', (ctx, next) => {
* // ...
* });
* ```
*
* When a route is matched, its path is available at `ctx._matchedRoute` and if named,
* the name is available at `ctx._matchedRouteName`
*
* Route paths will be translated to regular expressions using
* [path-to-regexp](https://github.com/pillarjs/path-to-regexp).
*
* Query strings will not be considered when matching requests.
*
* #### Named routes
*
* Routes can optionally have names. This allows generation of URLs and easy
* renaming of URLs during development.
*
* ```javascript
* router.get('user', '/users/:id', (ctx, next) => {
* // ...
* });
*
* router.url('user', 3);
* // => "/users/3"
* ```
*
* #### Multiple middleware
*
* Multiple middleware may be given:
*
* ```javascript
* router.get(
* '/users/:id',
* (ctx, next) => {
* return User.findOne(ctx.params.id).then(function(user) {
* ctx.user = user;
* next();
* });
* },
* ctx => {
* console.log(ctx.user);
* // => { id: 17, name: "Alex" }
* }
* );
* ```
*
* ### Nested routers
*
* Nesting routers is supported:
*
* ```javascript
* const forums = new Router();
* const posts = new Router();
*
* posts.get('/', (ctx, next) => {...});
* posts.get('/:pid', (ctx, next) => {...});
* forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());
*
* // responds to "/forums/123/posts" and "/forums/123/posts/123"
* app.use(forums.routes());
* ```
*
* #### Router prefixes
*
* Route paths can be prefixed at the router level:
*
* ```javascript
* const router = new Router({
* prefix: '/users'
* });
*
* router.get('/', ...); // responds to "/users"
* router.get('/:id', ...); // responds to "/users/:id"
* ```
*
* #### URL parameters
*
* Named route parameters are captured and added to `ctx.params`.
*
* ```javascript
* router.get('/:category/:title', (ctx, next) => {
* console.log(ctx.params);
* // => { category: 'programming', title: 'how-to-node' }
* });
* ```
*
* The [path-to-regexp](https://github.com/pillarjs/path-to-regexp) module is
* used to convert paths to regular expressions.
*
* @name get|put|post|patch|delete|del
* @memberof module:koa-router.prototype
* @param {String} path
* @param {Function=} middleware route middleware(s)
* @param {Function} callback route callback
* @returns {Router}
*/
for (var i = 0; i < methods.length; i++) {
function setMethodVerb(method) {
Router.prototype[method] = function(name, path, middleware) {
var middleware;
if (typeof path === "string" || path instanceof RegExp) {
middleware = Array.prototype.slice.call(arguments, 2);
} else {
middleware = Array.prototype.slice.call(arguments, 1);
path = name;
name = null;
}
this.register(path, [method], middleware, {
name: name
});
return this;
};
}
setMethodVerb(methods[i]);
}
// Alias for `router.delete()` because delete is a reserved word
Router.prototype.del = Router.prototype['delete'];
/**
* Use given middleware.
*
* Middleware run in the order they are defined by `.use()`. They are invoked
* sequentially, requests start at the first middleware and work their way
* "down" the middleware stack.
*
* @example
*
* ```javascript
* // session middleware will run before authorize
* router
* .use(session())
* .use(authorize());
*
* // use middleware only with given path
* router.use('/users', userAuth());
*
* // or with an array of paths
* router.use(['/users', '/admin'], userAuth());
*
* app.use(router.routes());
* ```
*
* @param {String=} path
* @param {Function} middleware
* @param {Function=} ...
* @returns {Router}
*/
Router.prototype.use = function () {
var router = this;
var middleware = Array.prototype.slice.call(arguments);
var path;
// support array of paths
if (Array.isArray(middleware[0]) && typeof middleware[0][0] === 'string') {
var arrPaths = middleware[0];
for (var i = 0; i < arrPaths.length; i++) {
var p = arrPaths[i];
router.use.apply(router, [p].concat(middleware.slice(1)));
}
return this;
}
var hasPath = typeof middleware[0] === 'string';
if (hasPath) {
path = middleware.shift();
}
for (var i = 0; i < middleware.length; i++) {
var m = middleware[i];
if (m.router) {
var cloneRouter = Object.assign(Object.create(Router.prototype), m.router, {
stack: m.router.stack.slice(0)
});
for (var j = 0; j < cloneRouter.stack.length; j++) {
var nestedLayer = cloneRouter.stack[j];
var cloneLayer = Object.assign(
Object.create(Layer.prototype),
nestedLayer
);
if (path) cloneLayer.setPrefix(path);
if (router.opts.prefix) cloneLayer.setPrefix(router.opts.prefix);
router.stack.push(cloneLayer);
cloneRouter.stack[j] = cloneLayer;
}
if (router.params) {
function setRouterParams(paramArr) {
var routerParams = paramArr;
for (var j = 0; j < routerParams.length; j++) {
var key = routerParams[j];
cloneRouter.param(key, router.params[key]);
}
}
setRouterParams(Object.keys(router.params));
}
} else {
router.register(path || '(.*)', [], m, { end: false, ignoreCaptures: !hasPath });
}
}
return this;
};
/**
* Set the path prefix for a Router instance that was already initialized.
*
* @example
*
* ```javascript
* router.prefix('/things/:thing_id')
* ```
*
* @param {String} prefix
* @returns {Router}
*/
Router.prototype.prefix = function (prefix) {
prefix = prefix.replace(/\/$/, '');
this.opts.prefix = prefix;
for (var i = 0; i < this.stack.length; i++) {
var route = this.stack[i];
route.setPrefix(prefix);
}
return this;
};
/**
* Returns router middleware which dispatches a route matching the request.
*
* @returns {Function}
*/
Router.prototype.routes = Router.prototype.middleware = function () {
var router = this;
var dispatch = function dispatch(ctx, next) {
debug('%s %s', ctx.method, ctx.path);
var path = router.opts.routerPath || ctx.routerPath || ctx.path;
var matched = router.match(path, ctx.method);
var layerChain, layer, i;
if (ctx.matched) {
ctx.matched.push.apply(ctx.matched, matched.path);
} else {
ctx.matched = matched.path;
}
ctx.router = router;
if (!matched.route) return next();
var matchedLayers = matched.pathAndMethod
var mostSpecificLayer = matchedLayers[matchedLayers.length - 1]
ctx._matchedRoute = mostSpecificLayer.path;
if (mostSpecificLayer.name) {
ctx._matchedRouteName = mostSpecificLayer.name;
}
layerChain = matchedLayers.reduce(function(memo, layer) {
memo.push(function(ctx, next) {
ctx.captures = layer.captures(path, ctx.captures);
ctx.params = layer.params(path, ctx.captures, ctx.params);
ctx.routerName = layer.name;
return next();
});
return memo.concat(layer.stack);
}, []);
return compose(layerChain)(ctx, next);
};
dispatch.router = this;
return dispatch;
};
/**
* Returns separate middleware for responding to `OPTIONS` requests with
* an `Allow` header containing the allowed methods, as well as responding
* with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
*
* @example
*
* ```javascript
* const Koa = require('koa');
* const Router = require('@koa/router');
*
* const app = new Koa();
* const router = new Router();
*
* app.use(router.routes());
* app.use(router.allowedMethods());
* ```
*
* **Example with [Boom](https://github.com/hapijs/boom)**
*
* ```javascript
* const Koa = require('koa');
* const Router = require('@koa/router');
* const Boom = require('boom');
*
* const app = new Koa();
* const router = new Router();
*
* app.use(router.routes());
* app.use(router.allowedMethods({
* throw: true,
* notImplemented: () => new Boom.notImplemented(),
* methodNotAllowed: () => new Boom.methodNotAllowed()
* }));
* ```
*
* @param {Object=} options
* @param {Boolean=} options.throw throw error instead of setting status and header
* @param {Function=} options.notImplemented throw the returned value in place of the default NotImplemented error
* @param {Function=} options.methodNotAllowed throw the returned value in place of the default MethodNotAllowed error
* @returns {Function}
*/
Router.prototype.allowedMethods = function (options) {
options = options || {};
var implemented = this.methods;
return function allowedMethods(ctx, next) {
return next().then(function() {
var allowed = {};
if (!ctx.status || ctx.status === 404) {
for (var i = 0; i < ctx.matched.length; i++) {
var route = ctx.matched[i];
for (var j = 0; j < route.methods.length; j++) {
var method = route.methods[j];
allowed[method] = method
}
}
var allowedArr = Object.keys(allowed);
if (!~implemented.indexOf(ctx.method)) {
if (options.throw) {
var notImplementedThrowable;
if (typeof options.notImplemented === 'function') {
notImplementedThrowable = options.notImplemented(); // set whatever the user returns from their function
} else {
notImplementedThrowable = new HttpError.NotImplemented();
}
throw notImplementedThrowable;
} else {
ctx.status = 501;
ctx.set('Allow', allowedArr.join(', '));
}
} else if (allowedArr.length) {
if (ctx.method === 'OPTIONS') {
ctx.status = 200;
ctx.body = '';
ctx.set('Allow', allowedArr.join(', '));
} else if (!allowed[ctx.method]) {
if (options.throw) {
var notAllowedThrowable;
if (typeof options.methodNotAllowed === 'function') {
notAllowedThrowable = options.methodNotAllowed(); // set whatever the user returns from their function
} else {
notAllowedThrowable = new HttpError.MethodNotAllowed();
}
throw notAllowedThrowable;
} else {
ctx.status = 405;
ctx.set('Allow', allowedArr.join(', '));
}
}
}
}
});
};
};
/**
* Register route with all methods.
*
* @param {String} name Optional.
* @param {String} path
* @param {Function=} middleware You may also pass multiple middleware.
* @param {Function} callback
* @returns {Router}
* @private
*/
Router.prototype.all = function (name, path, middleware) {
var middleware;
if (typeof path === 'string') {
middleware = Array.prototype.slice.call(arguments, 2);
} else {
middleware = Array.prototype.slice.call(arguments, 1);
path = name;
name = null;
}
this.register(path, methods, middleware, {
name: name
});
return this;
};
/**
* Redirect `source` to `destination` URL with optional 30x status `code`.
*
* Both `source` and `destination` can be route names.
*
* ```javascript
* router.redirect('/login', 'sign-in');
* ```
*
* This is equivalent to:
*
* ```javascript
* router.all('/login', ctx => {
* ctx.redirect('/sign-in');
* ctx.status = 301;
* });
* ```
*
* @param {String} source URL or route name.
* @param {String} destination URL or route name.
* @param {Number=} code HTTP status code (default: 301).
* @returns {Router}
*/
Router.prototype.redirect = function (source, destination, code) {
// lookup source route by name
if (source[0] !== '/') {
source = this.url(source);
}
// lookup destination route by name
if (destination[0] !== '/') {
destination = this.url(destination);
}
return this.all(source, ctx => {
ctx.redirect(destination);
ctx.status = code || 301;
});
};
/**
* Create and register a route.
*
* @param {String} path Path string.
* @param {Array.<String>} methods Array of HTTP verbs.
* @param {Function} middleware Multiple middleware also accepted.
* @returns {Layer}
* @private
*/
Router.prototype.register = function (path, methods, middleware, opts) {
opts = opts || {};
var router = this;
var stack = this.stack;
// support array of paths
if (Array.isArray(path)) {
for (var i = 0; i < path.length; i++) {
var curPath = path[i];
router.register.call(router, curPath, methods, middleware, opts);
}
return this;
}
// create route
var route = new Layer(path, methods, middleware, {
end: opts.end === false ? opts.end : true,
name: opts.name,
sensitive: opts.sensitive || this.opts.sensitive || false,
strict: opts.strict || this.opts.strict || false,
prefix: opts.prefix || this.opts.prefix || "",
ignoreCaptures: opts.ignoreCaptures
});
if (this.opts.prefix) {
route.setPrefix(this.opts.prefix);
}
// add parameter middleware
for (var i = 0; i < Object.keys(this.params).length; i++) {
var param = Object.keys(this.params)[i];
route.param(param, this.params[param]);
}
stack.push(route);
return route;
};
/**
* Lookup route with given `name`.
*
* @param {String} name
* @returns {Layer|false}
*/
Router.prototype.route = function (name) {
var routes = this.stack;
for (var len = routes.length, i=0; i<len; i++) {
if (routes[i].name && routes[i].name === name) {
return routes[i];
}
}
return false;
};
/**
* Generate URL for route. Takes a route name and map of named `params`.
*
* @example
*
* ```javascript
* router.get('user', '/users/:id', (ctx, next) => {
* // ...
* });
*
* router.url('user', 3);
* // => "/users/3"
*
* router.url('user', { id: 3 });
* // => "/users/3"
*
* router.use((ctx, next) => {
* // redirect to named route
* ctx.redirect(ctx.router.url('sign-in'));
* })
*
* router.url('user', { id: 3 }, { query: { limit: 1 } });
* // => "/users/3?limit=1"
*
* router.url('user', { id: 3 }, { query: "limit=1" });
* // => "/users/3?limit=1"
* ```
*
* @param {String} name route name
* @param {Object} params url parameters
* @param {Object} [options] options parameter
* @param {Object|String} [options.query] query options
* @returns {String|Error}
*/
Router.prototype.url = function (name, params) {
var route = this.route(name);
if (route) {
var args = Array.prototype.slice.call(arguments, 1);
return route.url.apply(route, args);
}
return new Error("No route found for name: " + name);
};
/**
* Match given `path` and return corresponding routes.
*
* @param {String} path
* @param {String} method
* @returns {Object.<path, pathAndMethod>} returns layers that matched path and
* path and method.
* @private
*/
Router.prototype.match = function (path, method) {
var layers = this.stack;
var layer;
var matched = {
path: [],
pathAndMethod: [],
route: false
};
for (var len = layers.length, i = 0; i < len; i++) {
layer = layers[i];
debug('test %s %s', layer.path, layer.regexp);
if (layer.match(path)) {
matched.path.push(layer);
if (layer.methods.length === 0 || ~layer.methods.indexOf(method)) {
matched.pathAndMethod.push(layer);
if (layer.methods.length) matched.route = true;
}
}
}
return matched;
};
/**
* Run middleware for named route parameters. Useful for auto-loading or
* validation.
*
* @example
*
* ```javascript
* router
* .param('user', (id, ctx, next) => {
* ctx.user = users[id];
* if (!ctx.user) return ctx.status = 404;
* return next();
* })
* .get('/users/:user', ctx => {
* ctx.body = ctx.user;
* })
* .get('/users/:user/friends', ctx => {
* return ctx.user.getFriends().then(function(friends) {
* ctx.body = friends;
* });
* })
* // /users/3 => {"id": 3, "name": "Alex"}
* // /users/3/friends => [{"id": 4, "name": "TJ"}]
* ```
*
* @param {String} param
* @param {Function} middleware
* @returns {Router}
*/
Router.prototype.param = function(param, middleware) {
this.params[param] = middleware;
for (var i = 0; i < this.stack.length; i++) {
var route = this.stack[i];
route.param(param, middleware);
}
return this;
};
/**
* Generate URL from url pattern and given `params`.
*
* @example
*
* ```javascript
* const url = Router.url('/users/:id', {id: 1});
* // => "/users/1"
* ```
*
* @param {String} path url pattern
* @param {Object} params url parameters
* @returns {String}
*/
Router.url = function (path) {
var args = Array.prototype.slice.call(arguments, 1);
return Layer.prototype.url.apply({ path: path }, args);
};
{
"_from": "@koa/router@^8.0.8",
"_id": "@koa/router@8.0.8",
"_inBundle": false,
"_integrity": "sha512-FnT93N4NUehnXr+juupDmG2yfi0JnWdCmNEuIXpCG4TtG+9xvtrLambBH3RclycopVUOEYAim2lydiNBI7IRVg==",
"_location": "/@koa/router",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@koa/router@^8.0.8",
"name": "@koa/router",
"escapedName": "@koa%2frouter",
"scope": "@koa",
"rawSpec": "^8.0.8",
"saveSpec": null,
"fetchSpec": "^8.0.8"
},
"_requiredBy": [
"/"
],
"_resolved": "https://registry.npmjs.org/@koa/router/-/router-8.0.8.tgz",
"_shasum": "95f32d11373d03d89dcb63fabe9ac6f471095236",
"_spec": "@koa/router@^8.0.8",
"_where": "/home/geo/development/cbdiscord/server",
"author": {
"name": "Alex Mingoia",
"email": "talk@alexmingoia.com"
},
"bugs": {
"url": "https://github.com/koajs/router/issues",
"email": "niftylettuce@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"debug": "^4.1.1",
"http-errors": "^1.7.3",
"koa-compose": "^4.1.0",
"methods": "^1.1.2",
"path-to-regexp": "1.x",
"urijs": "^1.19.2"
},
"deprecated": false,
"description": "Router middleware for koa. Provides RESTful resource routing.",
"devDependencies": {
"expect.js": "^0.3.1",
"jsdoc-to-markdown": "^5.0.3",
"koa": "^2.11.0",
"mocha": "^6.2.2",
"should": "^13.2.3",
"supertest": "^4.0.2"
},
"engines": {
"node": ">= 8.0.0"
},
"files": [
"lib"
],
"homepage": "https://github.com/koajs/router",
"keywords": [
"koa",
"middleware",
"route",
"router"
],
"license": "MIT",
"main": "lib/router.js",
"name": "@koa/router",
"repository": {
"type": "git",
"url": "git+https://github.com/koajs/koa-router.git"
},
"scripts": {
"docs": "NODE_ENV=test jsdoc2md -t ./lib/API_tpl.hbs --src ./lib/*.js >| API.md",
"test": "NODE_ENV=test mocha test/**/*.js"
},
"version": "8.0.8"
}
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/bluebird`
# Summary
This package contains type definitions for bluebird (https://github.com/petkaantonov/bluebird).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/bluebird.
### Additional Details
* Last updated: Mon, 02 Mar 2020 17:51:16 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Leonard Hecker](https://github.com/lhecker).
// Type definitions for bluebird 3.5
// Project: https://github.com/petkaantonov/bluebird
// Definitions by: Leonard Hecker <https://github.com/lhecker>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.2
/*!
* The code following this comment originates from:
* https://github.com/types/npm-bluebird
*
* Note for browser users: use bluebird-global typings instead of this one
* if you want to use Bluebird via the global Promise symbol.
*
* Licensed under:
* The MIT License (MIT)
*
* Copyright (c) 2016 unional
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
type Constructor<E> = new (...args: any[]) => E;
type CatchFilter<E> = ((error: E) => boolean) | (object & E);
type Resolvable<R> = R | PromiseLike<R>;
type IterateFunction<T, R> = (item: T, index: number, arrayLength: number) => Resolvable<R>;
declare class Bluebird<R> implements PromiseLike<R>, Bluebird.Inspection<R> {
readonly [Symbol.toStringTag]: "Object";
/**
* Create a new promise. The passed in function will receive functions
* `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
*
* If promise cancellation is enabled, passed in function will receive
* one more function argument `onCancel` that allows to register an optional cancellation callback.
*/
constructor(callback: (resolve: (thenableOrResult?: Resolvable<R>) => void, reject: (error?: any) => void, onCancel?: (callback: () => void) => void) => void);
/**
* Promises/A+ `.then()`. Returns a new promise chained from this promise.
*
* The new promise will be rejected or resolved depending on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
// Based on PromiseLike.then, but returns a Bluebird instance.
then<U>(onFulfill?: (value: R) => Resolvable<U>, onReject?: (error: any) => Resolvable<U>): Bluebird<U>; // For simpler signature help.
then<TResult1 = R, TResult2 = never>(
onfulfilled?: ((value: R) => Resolvable<TResult1>) | null,
onrejected?: ((reason: any) => Resolvable<TResult2>) | null
): Bluebird<TResult1 | TResult2>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise.
*
* Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch<U = R>(onReject: ((error: any) => Resolvable<U>) | undefined | null): Bluebird<U | R>;
/**
* This extends `.catch` to work more like catch-clauses in languages like Java or C#.
*
* Instead of manually checking `instanceof` or `.name === "SomeError"`,
* you may specify a number of error constructors which are eligible for this catch handler.
* The catch handler that is first met that has eligible constructors specified, is the one that will be called.
*
* This method also supports predicate-based filters.
* If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument.
* The return result of the predicate will be used determine whether the error handler should be called.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch<U, E1, E2, E3, E4, E5>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
filter4: Constructor<E4>,
filter5: Constructor<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3, E4, E5>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
filter4: Constructor<E4> | CatchFilter<E4>,
filter5: Constructor<E5> | CatchFilter<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3, E4>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
filter4: Constructor<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3, E4>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
filter4: Constructor<E4> | CatchFilter<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
onReject: (error: E1 | E2 | E3) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2, E3>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
onReject: (error: E1 | E2 | E3) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
onReject: (error: E1 | E2) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1, E2>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
onReject: (error: E1 | E2) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1>(
filter1: Constructor<E1>,
onReject: (error: E1) => Resolvable<U>,
): Bluebird<U | R>;
catch<U, E1>(
// tslint:disable-next-line:unified-signatures
filter1: Constructor<E1> | CatchFilter<E1>,
onReject: (error: E1) => Resolvable<U>,
): Bluebird<U | R>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise.
*
* Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
caught: Bluebird<R>["catch"];
/**
* Like `.catch` but instead of catching all types of exceptions,
* it only catches those that don't originate from thrown errors but rather from explicit rejections.
*/
error<U>(onReject: (reason: any) => Resolvable<U>): Bluebird<U>;
/**
* Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise.
*
* There are special semantics for `.finally()` in that the final value cannot be modified from the handler.
*
* Alias `.lastly();` for compatibility with earlier ECMAScript version.
*/
finally(handler: () => Resolvable<any>): Bluebird<R>;
lastly: Bluebird<R>["finally"];
/**
* Create a promise that follows this promise, but is bound to the given `thisArg` value.
* A bound promise will call its handlers with the bound value set to `this`.
*
* Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
*/
bind(thisArg: any): Bluebird<R>;
/**
* Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
*/
done<U>(onFulfilled?: (value: R) => Resolvable<U>, onRejected?: (error: any) => Resolvable<U>): void;
/**
* Like `.finally()`, but not called for rejections.
*/
tap(onFulFill: (value: R) => Resolvable<any>): Bluebird<R>;
/**
* Like `.catch()` but rethrows the error
*/
tapCatch(onReject: (error?: any) => Resolvable<any>): Bluebird<R>;
tapCatch<E1, E2, E3, E4, E5>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
filter4: Constructor<E4>,
filter5: Constructor<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3, E4, E5>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
filter4: Constructor<E4> | CatchFilter<E4>,
filter5: Constructor<E5> | CatchFilter<E5>,
onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3, E4>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
filter4: Constructor<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3, E4>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
filter4: Constructor<E4> | CatchFilter<E4>,
onReject: (error: E1 | E2 | E3 | E4) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
filter3: Constructor<E3>,
onReject: (error: E1 | E2 | E3) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2, E3>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
filter3: Constructor<E3> | CatchFilter<E3>,
onReject: (error: E1 | E2 | E3) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2>(
filter1: Constructor<E1>,
filter2: Constructor<E2>,
onReject: (error: E1 | E2) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1, E2>(
filter1: Constructor<E1> | CatchFilter<E1>,
filter2: Constructor<E2> | CatchFilter<E2>,
onReject: (error: E1 | E2) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1>(
filter1: Constructor<E1>,
onReject: (error: E1) => Resolvable<any>,
): Bluebird<R>;
tapCatch<E1>(
// tslint:disable-next-line:unified-signatures
filter1: Constructor<E1> | CatchFilter<E1>,
onReject: (error: E1) => Resolvable<any>,
): Bluebird<R>;
/**
* Same as calling `Promise.delay(ms, this)`.
*/
delay(ms: number): Bluebird<R>;
/**
* Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason.
* However, if this promise is not fulfilled or rejected within ms milliseconds, the returned promise
* is rejected with a TimeoutError or the error as the reason.
*
* You may specify a custom error message with the `message` parameter.
*/
timeout(ms: number, message?: string | Error): Bluebird<R>;
/**
* Register a node-style callback on this promise.
*
* When this promise is is either fulfilled or rejected,
* the node callback will be called back with the node.js convention
* where error reason is the first argument and success value is the second argument.
*
* The error argument will be `null` in case of success.
* If the `callback` argument is not a function, this method does not do anything.
*/
nodeify(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this;
nodeify(...sink: any[]): this;
asCallback(callback: (err: any, value?: R) => void, options?: Bluebird.SpreadOption): this;
asCallback(...sink: any[]): this;
/**
* See if this `promise` has been fulfilled.
*/
isFulfilled(): boolean;
/**
* See if this `promise` has been rejected.
*/
isRejected(): boolean;
/**
* See if this `promise` is still defer.
*/
isPending(): boolean;
/**
* See if this `promise` has been cancelled.
*/
isCancelled(): boolean;
/**
* See if this `promise` is resolved -> either fulfilled or rejected.
*/
isResolved(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet.
*
* throws `TypeError`
*/
reason(): any;
/**
* Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of
* the promise as snapshotted at the time of calling `.reflect()`.
*/
reflect(): Bluebird<Bluebird.Inspection<R>>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call<U extends keyof Q, Q>(this: Bluebird<Q>, propertyName: U, ...args: any[]): Bluebird<Q[U] extends (...args: any[]) => any ? ReturnType<Q[U]> : never>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* </code>
*/
get<U extends keyof R>(key: U): Bluebird<R[U]>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
*
* Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
*/
return(): Bluebird<void>;
return<U>(value: U): Bluebird<U>;
thenReturn(): Bluebird<void>;
thenReturn<U>(value: U): Bluebird<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.return()`.
*
* Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
*/
throw(reason: Error): Bluebird<never>;
thenThrow(reason: Error): Bluebird<never>;
/**
* Convenience method for:
*
* <code>
* .catch(function() {
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.catchReturn()`
*/
catchReturn<U>(value: U): Bluebird<R | U>;
// No need to be specific about Error types in these overrides, since there's no handler function
catchReturn<U>(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
filter4: Constructor<Error>,
filter5: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
filter4: Constructor<Error> | CatchFilter<Error>,
filter5: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
filter4: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
filter4: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
filter1: Constructor<Error>,
value: U,
): Bluebird<R | U>;
catchReturn<U>(
// tslint:disable-next-line:unified-signatures
filter1: Constructor<Error> | CatchFilter<Error>,
value: U,
): Bluebird<R | U>;
/**
* Convenience method for:
*
* <code>
* .catch(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.catchReturn()`.
*/
catchThrow(reason: Error): Bluebird<R>;
// No need to be specific about Error types in these overrides, since there's no handler function
catchThrow(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
filter4: Constructor<Error>,
filter5: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
filter4: Constructor<Error> | CatchFilter<Error>,
filter5: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
filter4: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
filter4: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
filter3: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
filter3: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error>,
filter2: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error> | CatchFilter<Error>,
filter2: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
filter1: Constructor<Error>,
reason: Error,
): Bluebird<R>;
catchThrow(
// tslint:disable-next-line:unified-signatures
filter1: Constructor<Error> | CatchFilter<Error>,
reason: Error,
): Bluebird<R>;
/**
* Convert to String.
*/
toString(): string;
/**
* This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`.
*/
toJSON(): object;
/**
* Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
*/
spread<U, Q>(this: Bluebird<R & Iterable<Q>>, fulfilledHandler: (...values: Q[]) => Resolvable<U>): Bluebird<U>;
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
all<Q>(this: Bluebird<R & Iterable<Q>>): Bluebird<R>;
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
all(): Bluebird<never>;
/**
* Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
props<K, V>(this: PromiseLike<Map<K, Resolvable<V>>>): Bluebird<Map<K, V>>;
props<T>(this: PromiseLike<Bluebird.ResolvableProps<T>>): Bluebird<T>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
any<Q>(this: Bluebird<R & Iterable<Q>>): Bluebird<Q>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
any(): Bluebird<never>;
/**
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
some<Q>(this: Bluebird<R & Iterable<Q>>, count: number): Bluebird<R>;
/**
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
some(count: number): Bluebird<never>;
/**
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
race<Q>(this: Bluebird<R & Iterable<Q>>): Bluebird<Q>;
/**
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
race(): Bluebird<never>;
/**
* Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
map<U, Q>(this: Bluebird<R & Iterable<Q>>, mapper: IterateFunction<Q, U>, options?: Bluebird.ConcurrencyOption): Bluebird<U[]>;
/**
* Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
reduce<U, Q>(this: Bluebird<R & Iterable<Q>>, reducer: (memo: U, item: Q, index: number, arrayLength: number) => Resolvable<U>, initialValue?: U): Bluebird<U>;
/**
* Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
filter<Q>(this: Bluebird<R & Iterable<Q>>, filterer: IterateFunction<Q, boolean>, options?: Bluebird.ConcurrencyOption): Bluebird<R>;
/**
* Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
each<Q>(this: Bluebird<R & Iterable<Q>>, iterator: IterateFunction<Q, any>): Bluebird<R>;
/**
* Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
mapSeries<U, Q>(this: Bluebird<R & Iterable<Q>>, iterator: IterateFunction<Q, U>): Bluebird<U[]>;
/**
* Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled
*/
cancel(): void;
/**
* Basically sugar for doing: somePromise.catch(function(){});
*
* Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting.
*/
suppressUnhandledRejections(): void;
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
* Note about second argument: if it's specifically a true array, its values become respective arguments for the function call.
* Otherwise it is passed as is as the first argument for the function call.
*
* Alias for `attempt();` for compatibility with earlier ECMAScript version.
*/
static try<R>(fn: () => Resolvable<R>): Bluebird<R>;
static attempt<R>(fn: () => Resolvable<R>): Bluebird<R>;
/**
* Returns a new function that wraps the given function `fn`.
* The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
* This method is convenient when a function can sometimes return synchronously or throw synchronously.
*/
static method<R>(fn: () => Resolvable<R>): () => Bluebird<R>;
static method<R, A1>(fn: (arg1: A1) => Resolvable<R>): (arg1: A1) => Bluebird<R>;
static method<R, A1, A2>(fn: (arg1: A1, arg2: A2) => Resolvable<R>): (arg1: A1, arg2: A2) => Bluebird<R>;
static method<R, A1, A2, A3>(fn: (arg1: A1, arg2: A2, arg3: A3) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<R>;
static method<R, A1, A2, A3, A4>(fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird<R>;
static method<R, A1, A2, A3, A4, A5>(fn: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Resolvable<R>): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird<R>;
static method<R>(fn: (...args: any[]) => Resolvable<R>): (...args: any[]) => Bluebird<R>;
/**
* Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state.
*/
static resolve(): Bluebird<void>;
static resolve<R>(value: Resolvable<R>): Bluebird<R>;
/**
* Create a promise that is rejected with the given `reason`.
*/
static reject(reason: any): Bluebird<never>;
/**
* @deprecated
* Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution).
* @see http://bluebirdjs.com/docs/deprecated-apis.html#promise-resolution
*/
static defer<R>(): Bluebird.Resolver<R>; // tslint:disable-line no-unnecessary-generics
/**
* Cast the given `value` to a trusted promise.
*
* If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value.
* If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable.
*/
static cast<R>(value: Resolvable<R>): Bluebird<R>;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
static bind(thisArg: any): Bluebird<void>;
/**
* See if `value` is a trusted Promise.
*/
static is(value: any): boolean;
/**
* Call this right after the library is loaded to enabled long stack traces.
*
* Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created.
* Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
*/
static longStackTraces(): void;
/**
* Returns a promise that will be resolved with value (or undefined) after given ms milliseconds.
* If value is a promise, the delay will start counting down when it is fulfilled and the returned
* promise will be fulfilled with the fulfillment value of the value promise.
*/
static delay<R>(ms: number, value: Resolvable<R>): Bluebird<R>;
static delay(ms: number): Bluebird<void>;
/**
* Returns a function that will wrap the given `nodeFunction`.
*
* Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function.
* The node function should conform to node.js convention of accepting a callback as last argument and
* calling that callback with error as the first argument and success value on the second argument.
*
* If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them.
*
* If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`.
*/
static promisify<T>(
func: (callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): () => Bluebird<T>;
static promisify<T, A1>(
func: (arg1: A1, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1) => Bluebird<T>;
static promisify<T, A1, A2>(
func: (arg1: A1, arg2: A2, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1, arg2: A2) => Bluebird<T>;
static promisify<T, A1, A2, A3>(
func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1, arg2: A2, arg3: A3) => Bluebird<T>;
static promisify<T, A1, A2, A3, A4>(
func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Bluebird<T>;
static promisify<T, A1, A2, A3, A4, A5>(
func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result?: T) => void) => void,
options?: Bluebird.PromisifyOptions
): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Bluebird<T>;
static promisify(nodeFunction: (...args: any[]) => void, options?: Bluebird.PromisifyOptions): (...args: any[]) => Bluebird<any>;
/**
* Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain.
*
* The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
*
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example,
* if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
// TODO how to model promisifyAll?
static promisifyAll<T extends object>(target: T, options?: Bluebird.PromisifyAllOptions<T>): T;
/**
* Returns a promise that is resolved by a node style callback function.
*/
static fromNode<T>(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird<T>;
static fromCallback<T>(resolver: (callback: (err: any, result?: T) => void) => void, options?: Bluebird.FromNodeOptions): Bluebird<T>;
/**
* Returns a function that can use `yield` to run asynchronous code synchronously.
*
* This feature requires the support of generators which are drafted in the next version of the language.
* Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO: After https://github.com/Microsoft/TypeScript/issues/2983 is implemented, we can use
// the return type propagation of generators to automatically infer the return type T.
static coroutine<T>(
generatorFunction: () => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): () => Bluebird<T>;
static coroutine<T, A1>(
generatorFunction: (a1: A1) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1) => Bluebird<T>;
static coroutine<T, A1, A2>(
generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2) => Bluebird<T>;
static coroutine<T, A1, A2, A3>(
generatorFunction: (a1: A1, a2: A2, a3: A3) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4, A5>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4, A5, A6>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4, A5, A6, A7>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => Bluebird<T>;
static coroutine<T, A1, A2, A3, A4, A5, A6, A7, A8>(
generatorFunction: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => IterableIterator<any>,
options?: Bluebird.CoroutineOptions
): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => Bluebird<T>;
/**
* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*/
static onPossiblyUnhandledRejection(handler: (reason: any) => any): void;
/**
* Add handler as the handler to call when there is a possibly unhandled rejection.
* The default handler logs the error stack to stderr or console.error in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*
* Note: this hook is specific to the bluebird instance its called on, application developers should use global rejection events.
*/
static onPossiblyUnhandledRejection(handler?: (error: Error, promise: Bluebird<any>) => void): void;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled.
* The promise's fulfillment value is an array with fulfillment values at respective positions to the original array.
* If any promise in the array rejects, the returned promise is rejected with the rejection reason.
*/
// TODO enable more overloads
// array with promises of different types
static all<T1, T2, T3, T4, T5>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>, Resolvable<T5>]): Bluebird<[T1, T2, T3, T4, T5]>;
static all<T1, T2, T3, T4>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>, Resolvable<T4>]): Bluebird<[T1, T2, T3, T4]>;
static all<T1, T2, T3>(values: [Resolvable<T1>, Resolvable<T2>, Resolvable<T3>]): Bluebird<[T1, T2, T3]>;
static all<T1, T2>(values: [Resolvable<T1>, Resolvable<T2>]): Bluebird<[T1, T2]>;
static all<T1>(values: [Resolvable<T1>]): Bluebird<[T1]>;
// array with values
static all<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R[]>;
/**
* Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled.
*
* The promise's fulfillment value is an object with fulfillment values at respective keys to the original object.
* If any promise in the object rejects, the returned promise is rejected with the rejection reason.
*
* If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties.
* All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
*
* *The original object is not modified.*
*/
// map
static props<K, V>(map: Resolvable<Map<K, Resolvable<V>>>): Bluebird<Map<K, V>>;
// trusted promise for object
static props<T>(object: PromiseLike<Bluebird.ResolvableProps<T>>): Bluebird<T>; // tslint:disable-line:unified-signatures
// object
static props<T>(object: Bluebird.ResolvableProps<T>): Bluebird<T>; // tslint:disable-line:unified-signatures
/**
* Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly.
*/
static any<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is
* fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value.
*
* **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending.
*/
static race<R>(values: Resolvable<Iterable<Resolvable<R>>>): Bluebird<R>;
/**
* Initiate a competitive race between multiple promises or values (values will become immediately fulfilled promises).
* When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of
* the winners in order of resolution.
*
* If too many promises are rejected so that the promise can never become fulfilled,
* it will be immediately rejected with an array of rejection reasons in the order they were thrown in.
*
* *The original array is not modified.*
*/
static some<R>(values: Resolvable<Iterable<Resolvable<R>>>, count: number): Bluebird<R[]>;
/**
* Promise.join(
* Promise<any>|any values...,
* function handler
* ) -> Promise
* For coordinating multiple concurrent discrete promises.
*
* Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array.
* This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply
*/
static join<R, A1>(
arg1: Resolvable<A1>,
handler: (arg1: A1) => Resolvable<R>
): Bluebird<R>;
static join<R, A1, A2>(
arg1: Resolvable<A1>,
arg2: Resolvable<A2>,
handler: (arg1: A1, arg2: A2) => Resolvable<R>
): Bluebird<R>;
static join<R, A1, A2, A3>(
arg1: Resolvable<A1>,
arg2: Resolvable<A2>,
arg3: Resolvable<A3>,
handler: (arg1: A1, arg2: A2, arg3: A3) => Resolvable<R>
): Bluebird<R>;
static join<R, A1, A2, A3, A4>(
arg1: Resolvable<A1>,
arg2: Resolvable<A2>,
arg3: Resolvable<A3>,
arg4: Resolvable<A4>,
handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Resolvable<R>
): Bluebird<R>;
static join<R, A1, A2, A3, A4, A5>(
arg1: Resolvable<A1>,
arg2: Resolvable<A2>,
arg3: Resolvable<A3>,
arg4: Resolvable<A4>,
arg5: Resolvable<A5>,
handler: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Resolvable<R>
): Bluebird<R>;
// variadic array
/** @deprecated use .all instead */
static join<R>(...values: Array<Resolvable<R>>): Bluebird<R[]>;
/**
* Map an array, or a promise of an array,
* which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
*
* *The original array is not modified.*
*/
static map<R, U>(
values: Resolvable<Iterable<Resolvable<R>>>,
mapper: IterateFunction<R, U>,
options?: Bluebird.ConcurrencyOption
): Bluebird<U[]>;
/**
* Reduce an array, or a promise of an array,
* which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*
* *The original array is not modified. If no `initialValue` is given and the array doesn't contain at least 2 items,
* the callback will not be called and `undefined` is returned.
*
* If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
*/
static reduce<R, U>(
values: Resolvable<Iterable<Resolvable<R>>>,
reducer: (total: U, current: R, index: number, arrayLength: number) => Resolvable<U>,
initialValue?: U
): Bluebird<U>;
/**
* Filter an array, or a promise of an array,
* which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result.
*
* *The original array is not modified.
*/
static filter<R>(
values: Resolvable<Iterable<Resolvable<R>>>,
filterer: IterateFunction<R, boolean>,
option?: Bluebird.ConcurrencyOption
): Bluebird<R[]>;
/**
* Iterate over an array, or a promise of an array,
* which contains promises (or a mix of promises and values) with the given iterator function with the signature `(item, index, value)`
* where item is the resolved value of a respective promise in the input array.
* Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well.
*
* Resolves to the original array unmodified, this method is meant to be used for side effects.
* If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*/
static each<R>(
values: Resolvable<Iterable<Resolvable<R>>>,
iterator: IterateFunction<R, any>
): Bluebird<R[]>;
/**
* Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values),
* iterate over all the values in the Iterable into an array and iterate over the array serially, in-order.
*
* Returns a promise for an array that contains the values returned by the iterator function in their respective positions.
* The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled.
* This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach.
*
* If any promise in the input array is rejected or any promise returned by the iterator function is rejected, the result will be rejected as well.
*/
static mapSeries<R, U>(
values: Resolvable<Iterable<Resolvable<R>>>,
iterator: IterateFunction<R, U>
): Bluebird<U[]>;
/**
* A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`.
*
* Returns a Disposer object which encapsulates both the resource as well as the method to clean it up.
* The user can pass this object to `Promise.using` to get access to the resource when it becomes available,
* as well as to ensure its automatically cleaned up.
*
* The second argument passed to a disposer is the result promise of the using block, which you can
* inspect synchronously.
*/
disposer(disposeFn: (arg: R, promise: Bluebird<R>) => Resolvable<void>): Bluebird.Disposer<R>;
/**
* In conjunction with `.disposer`, using will make sure that no matter what, the specified disposer
* will be called when the promise returned by the callback passed to using has settled. The disposer is
* necessary because there is no standard interface in node for disposing resources.
*/
static using<R, T>(
disposer: Bluebird.Disposer<R>,
executor: (transaction: R) => PromiseLike<T>
): Bluebird<T>;
static using<R1, R2, T>(
disposer: Bluebird.Disposer<R1>,
disposer2: Bluebird.Disposer<R2>,
executor: (transaction1: R1, transaction2: R2
) => PromiseLike<T>): Bluebird<T>;
static using<R1, R2, R3, T>(
disposer: Bluebird.Disposer<R1>,
disposer2: Bluebird.Disposer<R2>,
disposer3: Bluebird.Disposer<R3>,
executor: (transaction1: R1, transaction2: R2, transaction3: R3) => PromiseLike<T>
): Bluebird<T>;
/**
* Configure long stack traces, warnings, monitoring and cancellation.
* Note that even though false is the default here, a development environment might be detected which automatically
* enables long stack traces and warnings.
*/
static config(options: {
/** Enable warnings */
warnings?: boolean | {
/** Enables all warnings except forgotten return statements. */
wForgottenReturn: boolean;
};
/** Enable long stack traces */
longStackTraces?: boolean;
/** Enable cancellation */
cancellation?: boolean;
/** Enable monitoring */
monitoring?: boolean;
}): void;
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
* If promise cancellation is enabled, passed in function will receive one more function argument `onCancel` that allows to register an optional cancellation callback.
*/
static Promise: typeof Bluebird;
/**
* The version number of the library
*/
static version: string;
}
declare namespace Bluebird {
interface ConcurrencyOption {
concurrency: number;
}
interface SpreadOption {
spread: boolean;
}
interface FromNodeOptions {
multiArgs?: boolean;
}
interface PromisifyOptions {
context?: any;
multiArgs?: boolean;
}
interface PromisifyAllOptions<T> extends PromisifyOptions {
suffix?: string;
filter?(name: string, func: (...args: any[]) => any, target?: any, passesDefaultFilter?: boolean): boolean;
// The promisifier gets a reference to the original method and should return a function which returns a promise
promisifier?(this: T, originalMethod: (...args: any[]) => any, defaultPromisifer: (...args: any[]) => (...args: any[]) => Bluebird<any>): () => PromiseLike<any>;
}
interface CoroutineOptions {
yieldHandler(value: any): any;
}
/**
* Represents an error is an explicit promise rejection as opposed to a thrown error.
* For example, if an error is errbacked by a callback API promisified through undefined or undefined
* and is not a typed error, it will be converted to a `OperationalError` which has the original error in
* the `.cause` property.
*
* `OperationalError`s are caught in `.error` handlers.
*/
class OperationalError extends Error { }
/**
* Signals that an operation has timed out. Used as a custom cancellation reason in `.timeout`.
*/
class TimeoutError extends Error { }
/**
* Signals that an operation has been aborted or cancelled. The default reason used by `.cancel`.
*/
class CancellationError extends Error { }
/**
* A collection of errors. `AggregateError` is an array-like object, with numeric indices and a `.length` property.
* It supports all generic array methods such as `.forEach` directly.
*
* `AggregateError`s are caught in `.error` handlers, even if the contained errors are not operational.
*
* `Promise.some` and `Promise.any` use `AggregateError` as rejection reason when they fail.
*/
class AggregateError extends Error implements ArrayLike<Error> {
length: number;
[index: number]: Error;
join(separator?: string): string;
pop(): Error;
push(...errors: Error[]): number;
shift(): Error;
unshift(...errors: Error[]): number;
slice(begin?: number, end?: number): AggregateError;
filter(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError;
forEach(callback: (element: Error, index: number, array: AggregateError) => void, thisArg?: any): undefined;
some(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean;
every(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): boolean;
map(callback: (element: Error, index: number, array: AggregateError) => boolean, thisArg?: any): AggregateError;
indexOf(searchElement: Error, fromIndex?: number): number;
lastIndexOf(searchElement: Error, fromIndex?: number): number;
reduce(callback: (accumulator: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any;
reduceRight(callback: (previousValue: any, element: Error, index: number, array: AggregateError) => any, initialValue?: any): any;
sort(compareFunction?: (errLeft: Error, errRight: Error) => number): AggregateError;
reverse(): AggregateError;
}
/**
* returned by `Bluebird.disposer()`.
*/
class Disposer<R> { }
/** @deprecated Use PromiseLike<T> directly. */
type Thenable<T> = PromiseLike<T>;
type ResolvableProps<T> = object & {[K in keyof T]: Resolvable<T[K]>};
interface Resolver<R> {
/**
* Returns a reference to the controlled promise that can be passed to clients.
*/
promise: Bluebird<R>;
/**
* Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state.
*/
resolve(value: R): void;
resolve(): void;
/**
* Reject the underlying promise with `reason` as the rejection reason.
*/
reject(reason: any): void;
/**
* Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property.
* The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
*
* If the the callback is called with multiple success values, the resolver fulfills its promise with an array of the values.
*/
// TODO specify resolver callback
callback(err: any, value: R, ...values: R[]): void;
}
interface Inspection<R> {
/**
* See if the underlying promise was fulfilled at the creation time of this inspection object.
*/
isFulfilled(): boolean;
/**
* See if the underlying promise was rejected at the creation time of this inspection object.
*/
isRejected(): boolean;
/**
* See if the underlying promise was cancelled at the creation time of this inspection object.
*/
isCancelled(): boolean;
/**
* See if the underlying promise was defer at the creation time of this inspection object.
*/
isPending(): boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object.
*
* throws `TypeError`
*/
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object.
*
* throws `TypeError`
*/
reason(): any;
}
/**
* Returns a new independent copy of the Bluebird library.
*
* This method should be used before you use any of the methods which would otherwise alter the global Bluebird object - to avoid polluting global state.
*/
function getNewLibraryCopy(): typeof Bluebird;
/**
* This is relevant to browser environments with no module loader.
*
* Release control of the Promise namespace to whatever it was before this library was loaded.
* Returns a reference to the library namespace so you can attach it to something else.
*/
function noConflict(): typeof Bluebird;
/**
* Changes how bluebird schedules calls a-synchronously.
*
* @param scheduler Should be a function that asynchronously schedules
* the calling of the passed in function
*/
function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void;
}
export = Bluebird;
{
"_from": "@types/bluebird@^3.5.26",
"_id": "@types/bluebird@3.5.30",
"_inBundle": false,
"_integrity": "sha512-8LhzvcjIoqoi1TghEkRMkbbmM+jhHnBokPGkJWjclMK+Ks0MxEBow3/p2/iFTZ+OIbJHQDSfpgdZEb+af3gfVw==",
"_location": "/@types/bluebird",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@types/bluebird@^3.5.26",
"name": "@types/bluebird",
"escapedName": "@types%2fbluebird",
"scope": "@types",
"rawSpec": "^3.5.26",
"saveSpec": null,
"fetchSpec": "^3.5.26"
},
"_requiredBy": [
"/promise-mysql"
],
"_resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.30.tgz",
"_shasum": "ee034a0eeea8b84ed868b1aa60d690b08a6cfbc5",
"_spec": "@types/bluebird@^3.5.26",
"_where": "/home/geo/development/cbdiscord/server/node_modules/promise-mysql",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Leonard Hecker",
"url": "https://github.com/lhecker"
}
],
"dependencies": {},
"deprecated": false,
"description": "TypeScript definitions for bluebird",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
"license": "MIT",
"main": "",
"name": "@types/bluebird",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/bluebird"
},
"scripts": {},
"typeScriptVersion": "3.2",
"types": "index.d.ts",
"typesPublisherContentHash": "05934c80eb0627b355732c82a1250d35cee649b4d57a03c7b3c98f8384c9364a",
"version": "3.5.30"
}
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/events`
# Summary
This package contains type definitions for events (https://github.com/Gozala/events).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/events
Additional Details
* Last updated: Thu, 24 Jan 2019 03:19:08 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by Yasunori Ohoka <https://github.com/yasupeke>, Shenwei Wang <https://github.com/weareoutman>.
// Type definitions for events 3.0
// Project: https://github.com/Gozala/events
// Definitions by: Yasunori Ohoka <https://github.com/yasupeke>
// Shenwei Wang <https://github.com/weareoutman>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export type Listener = (...args: any[]) => void;
export class EventEmitter {
static listenerCount(emitter: EventEmitter, type: string | number): number;
static defaultMaxListeners: number;
eventNames(): Array<string | number>;
setMaxListeners(n: number): this;
getMaxListeners(): number;
emit(type: string | number, ...args: any[]): boolean;
addListener(type: string | number, listener: Listener): this;
on(type: string | number, listener: Listener): this;
once(type: string | number, listener: Listener): this;
prependListener(type: string | number, listener: Listener): this;
prependOnceListener(type: string | number, listener: Listener): this;
removeListener(type: string | number, listener: Listener): this;
off(type: string | number, listener: Listener): this;
removeAllListeners(type?: string | number): this;
listeners(type: string | number): Listener[];
listenerCount(type: string | number): number;
rawListeners(type: string | number): Listener[];
}
{
"_from": "@types/events@*",
"_id": "@types/events@3.0.0",
"_inBundle": false,
"_integrity": "sha512-EaObqwIvayI5a8dCzhFrjKzVwKLxjoG9T6Ppd5CEo07LRKfQ8Yokw54r5+Wq7FaBQ+yXRvQAYPrHwya1/UFt9g==",
"_location": "/@types/events",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@types/events@*",
"name": "@types/events",
"escapedName": "@types%2fevents",
"scope": "@types",
"rawSpec": "*",
"saveSpec": null,
"fetchSpec": "*"
},
"_requiredBy": [
"/@types/formidable"
],
"_resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.0.tgz",
"_shasum": "2862f3f58a9a7f7c3e78d79f130dd4d71c25c2a7",
"_spec": "@types/events@*",
"_where": "/home/geo/development/cbdiscord/server/node_modules/@types/formidable",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Yasunori Ohoka",
"url": "https://github.com/yasupeke"
},
{
"name": "Shenwei Wang",
"url": "https://github.com/weareoutman"
}
],
"dependencies": {},
"deprecated": false,
"description": "TypeScript definitions for events",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
"license": "MIT",
"main": "",
"name": "@types/events",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
},
"scripts": {},
"typeScriptVersion": "2.0",
"types": "index",
"typesPublisherContentHash": "ae078136220837864b64cc7c1c5267ca1ceb809166fb74569e637bc7de9f2e12",
"version": "3.0.0"
}
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/formidable`
# Summary
This package contains type definitions for Formidable (https://github.com/felixge/node-formidable/).
# Details
Files were exported from https://www.github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/formidable
Additional Details
* Last updated: Mon, 09 Apr 2018 17:46:20 GMT
* Dependencies: http, stream, events, node
* Global values: none
# Credits
These definitions were written by Wim Looman <https://github.com/Nemo157>.
// Type definitions for Formidable 1.0.16
// Project: https://github.com/felixge/node-formidable/
// Definitions by: Wim Looman <https://github.com/Nemo157>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import http = require("http");
import stream = require("stream");
import events = require("events");
export declare class IncomingForm extends events.EventEmitter {
encoding: string;
uploadDir: string;
keepExtensions: boolean;
maxFileSize: number;
maxFieldsSize: number;
maxFields: number;
hash: string | boolean;
multiples: boolean;
type: string;
bytesReceived: number;
bytesExpected: number;
onPart: (part: Part) => void;
handlePart(part: Part): void;
parse(req: http.IncomingMessage, callback?: (err: any, fields: Fields, files: Files) => any): void;
}
export interface Fields {
[key: string]: string|Array<string>;
}
export interface Files {
[key: string]: File; // | File[];
}
export interface Part extends stream.Stream {
headers: { [key: string]: string };
name: string;
filename?: string;
mime?: string;
}
export interface File {
size: number;
path: string;
name: string;
type: string;
lastModifiedDate?: Date;
hash?: string;
toJSON(): Object;
}
{
"_from": "@types/formidable@^1.0.31",
"_id": "@types/formidable@1.0.31",
"_inBundle": false,
"_integrity": "sha512-dIhM5t8lRP0oWe2HF8MuPvdd1TpPTjhDMAqemcq6oIZQCBQTovhBAdTQ5L5veJB4pdQChadmHuxtB0YzqvfU3Q==",
"_location": "/@types/formidable",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@types/formidable@^1.0.31",
"name": "@types/formidable",
"escapedName": "@types%2fformidable",
"scope": "@types",
"rawSpec": "^1.0.31",
"saveSpec": null,
"fetchSpec": "^1.0.31"
},
"_requiredBy": [
"/koa-body"
],
"_resolved": "https://registry.npmjs.org/@types/formidable/-/formidable-1.0.31.tgz",
"_shasum": "274f9dc2d0a1a9ce1feef48c24ca0859e7ec947b",
"_spec": "@types/formidable@^1.0.31",
"_where": "/home/geo/development/cbdiscord/server/node_modules/koa-body",
"bugs": {
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Wim Looman",
"url": "https://github.com/Nemo157"
}
],
"dependencies": {
"@types/events": "*",
"@types/node": "*"
},
"deprecated": false,
"description": "TypeScript definitions for Formidable",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme",
"license": "MIT",
"main": "",
"name": "@types/formidable",
"repository": {
"type": "git",
"url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git"
},
"scripts": {},
"typeScriptVersion": "2.0",
"typesPublisherContentHash": "f25dea57419b31a9ce78e1d4cbcb2cd2044fc06f587b18cf269fc8e08aed9319",
"version": "1.0.31"
}
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
# Installation
> `npm install --save @types/mysql`
# Summary
This package contains type definitions for mysql (https://github.com/mysqljs/mysql).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mysql.
### Additional Details
* Last updated: Tue, 25 Feb 2020 18:40:45 GMT
* Dependencies: [@types/node](https://npmjs.com/package/@types/node)
* Global values: none
# Credits
These definitions were written by [ William Johnston](https://github.com/wjohnsto), [Kacper Polak](https://github.com/kacepe), [Krittanan Pingclasai](https://github.com/kpping), and [James Munro](https://github.com/jdmunro).
// Type definitions for mysql 2.15
// Project: https://github.com/mysqljs/mysql
// Definitions by: William Johnston <https://github.com/wjohnsto>
// Kacper Polak <https://github.com/kacepe>
// Krittanan Pingclasai <https://github.com/kpping>
// James Munro <https://github.com/jdmunro>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
/// <reference types="node" />
import stream = require("stream");
import tls = require("tls");
export interface EscapeFunctions {
/**
* Escape an untrusted string to be used as a SQL value. Use this on user
* provided data.
* @param value Value to escape
* @param stringifyObjects If true, don't convert objects into SQL lists
* @param timeZone Convert dates from UTC to the given timezone.
*/
escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
/**
* Escape an untrusted string to be used as a SQL identifier (database,
* table, or column name). Use this on user provided data.
* @param value Value to escape.
* @param forbidQualified Don't allow qualified identifiers (eg escape '.')
*/
escapeId(value: string, forbidQualified?: boolean): string;
/**
* Safely format a SQL query containing multiple untrusted values.
* @param sql Query, with insertion points specified with ? (for values) or
* ?? (for identifiers)
* @param values Array of objects to insert.
* @param stringifyObjects If true, don't convert objects into SQL lists
* @param timeZone Convert dates from UTC to the given timezone.
*/
format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string;
}
/**
* Escape an untrusted string to be used as a SQL value. Use this on user
* provided data.
* @param value Value to escape
* @param stringifyObjects If true, don't convert objects into SQL lists
* @param timeZone Convert dates from UTC to the given timezone.
*/
export function escape(value: any, stringifyObjects?: boolean, timeZone?: string): string;
/**
* Escape an untrusted string to be used as a SQL identifier (database,
* table, or column name). Use this on user provided data.
* @param value Value to escape.
* @param forbidQualified Don't allow qualified identifiers (eg escape '.')
*/
export function escapeId(value: string, forbidQualified?: boolean): string;
/**
* Safely format a SQL query containing multiple untrusted values.
* @param sql Query, with insertion points specified with ? (for values) or
* ?? (for identifiers)
* @param values Array of objects to insert.
* @param stringifyObjects If true, don't convert objects into SQL lists
* @param timeZone Convert dates from UTC to the given timezone.
*/
export function format(sql: string, values: any[], stringifyObjects?: boolean, timeZone?: string): string;
export function createConnection(connectionUri: string | ConnectionConfig): Connection;
export function createPool(config: PoolConfig | string): Pool;
export function createPoolCluster(config?: PoolClusterConfig): PoolCluster;
/**
* Create a string that will be inserted unescaped with format(), escape().
* Note: the value will still be escaped if used as an identifier (??) by
* format().
* @param sql
*/
export function raw(sql: string): () => string;
export interface Connection extends EscapeFunctions {
config: ConnectionConfig;
state: 'connected' | 'authenticated' | 'disconnected' | 'protocol_error' | string;
threadId: number | null;
createQuery: QueryFunction;
connect(callback?: (err: MysqlError, ...args: any[]) => void): void;
connect(options: any, callback?: (err: MysqlError, ...args: any[]) => void): void;
changeUser(options: ConnectionOptions, callback?: (err: MysqlError) => void): void;
changeUser(callback: (err: MysqlError) => void): void;
beginTransaction(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
beginTransaction(callback: (err: MysqlError) => void): void;
commit(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
commit(callback: (err: MysqlError) => void): void;
rollback(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
rollback(callback: (err: MysqlError) => void): void;
query: QueryFunction;
ping(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
ping(callback: (err: MysqlError) => void): void;
statistics(options?: QueryOptions, callback?: (err: MysqlError) => void): void;
statistics(callback: (err: MysqlError) => void): void;
/**
* Close the connection. Any queued data (eg queries) will be sent first. If
* there are any fatal errors, the connection will be immediately closed.
* @param callback Handler for any fatal error
*/
end(callback?: (err: MysqlError, ...args: any[]) => void): void;
end(options: any, callback: (err: MysqlError, ...args: any[]) => void): void;
/**
* Close the connection immediately, without waiting for any queued data (eg
* queries) to be sent. No further events or callbacks will be triggered.
*/
destroy(): void;
/**
* Pause the connection. No more 'result' events will fire until resume() is
* called.
*/
pause(): void;
/**
* Resume the connection.
*/
resume(): void;
on(ev: 'drain' | 'connect', callback: () => void): Connection;
/**
* Set handler to be run when the connection is closed.
*/
on(ev: 'end', callback: (err?: MysqlError) => void): Connection;
on(ev: 'fields', callback: (fields: any[]) => void): Connection;
/**
* Set handler to be run when a a fatal error occurs.
*/
on(ev: 'error', callback: (err: MysqlError) => void): Connection;
/**
* Set handler to be run when a callback has been queued to wait for an
* available connection.
*/
// tslint:disable-next-line:unified-signatures
on(ev: 'enqueue', callback: (err?: MysqlError) => void): Connection;
/**
* Set handler to be run on a certain event.
*/
on(ev: string, callback: (...args: any[]) => void): Connection;
}
export interface PoolConnection extends Connection {
release(): void;
/**
* Close the connection. Any queued data (eg queries) will be sent first. If
* there are any fatal errors, the connection will be immediately closed.
* @param callback Handler for any fatal error
*/
end(): void;
/**
* Close the connection immediately, without waiting for any queued data (eg
* queries) to be sent. No further events or callbacks will be triggered.
*/
destroy(): void;
}
export interface Pool extends EscapeFunctions {
config: PoolConfig;
getConnection(callback: (err: MysqlError, connection: PoolConnection) => void): void;
acquireConnection(connection: PoolConnection, callback: (err: MysqlError, connection: PoolConnection) => void): void;
releaseConnection(connection: PoolConnection): void;
/**
* Close the connection. Any queued data (eg queries) will be sent first. If
* there are any fatal errors, the connection will be immediately closed.
* @param callback Handler for any fatal error
*/
end(callback?: (err: MysqlError) => void): void;
query: QueryFunction;
/**
* Set handler to be run when a new connection is made within the pool.
*/
on(ev: 'connection', callback: (connection: PoolConnection) => void): Pool;
/**
* Set handler to be run when a connection is acquired from the pool. This
* is called after all acquiring activity has been performed on the
* connection, right before the connection is handed to the callback of the
* acquiring code.
*/
// tslint:disable-next-line:unified-signatures
on(ev: 'acquire', callback: (connection: PoolConnection) => void): Pool;
/**
* Set handler to be run when a connection is released back to the pool.
* This is called after all release activity has been performed on the
* connection, so the connection will be listed as free at the time of the
* event.
*/
// tslint:disable-next-line:unified-signatures
on(ev: 'release', callback: (connection: PoolConnection) => void): Pool;
/**
* Set handler to be run when a a fatal error occurs.
*/
on(ev: 'error', callback: (err: MysqlError) => void): Pool;
/**
* Set handler to be run when a callback has been queued to wait for an
* available connection.
*/
on(ev: 'enqueue', callback: (err?: MysqlError) => void): Pool;
/**
* Set handler to be run on a certain event.
*/
on(ev: string, callback: (...args: any[]) => void): Pool;
}
export interface PoolCluster {
config: PoolClusterConfig;
add(config: PoolConfig): void;
add(id: string, config: PoolConfig): void;
/**
* Close the connection. Any queued data (eg queries) will be sent first. If
* there are any fatal errors, the connection will be immediately closed.
* @param callback Handler for any fatal error
*/
end(callback?: (err: MysqlError) => void): void;
of(pattern: string, selector?: string): Pool;
of(pattern: undefined | null | false, selector: string): Pool;
/**
* remove all pools which match pattern
*/
remove(pattern: string): void;
getConnection(callback: (err: MysqlError, connection: PoolConnection) => void): void;
getConnection(pattern: string, callback: (err: MysqlError, connection: PoolConnection) => void): void;
getConnection(pattern: string, selector: string, callback: (err: MysqlError, connection: PoolConnection) => void): void;
/**
* Set handler to be run on a certain event.
*/
on(ev: string, callback: (...args: any[]) => void): PoolCluster;
/**
* Set handler to be run when a node is removed or goes offline.
*/
on(ev: 'remove' | 'offline', callback: (nodeId: string) => void): PoolCluster;
}
// related to Query
export type packetCallback = (packet: any) => void;
export interface Query {
/**
* Template query
*/
sql: string;
/**
* Values for template query
*/
values?: string[];
/**
* Default true
*/
typeCast?: TypeCast;
/**
* Default false
*/
nestedTables: boolean;
/**
* Emits a query packet to start the query
*/
start(): void;
/**
* Determines the packet class to use given the first byte of the packet.
*
* @param byte The first byte of the packet
* @param parser The packet parser
*/
determinePacket(byte: number, parser: any): any;
OkPacket: packetCallback;
ErrorPacket: packetCallback;
ResultSetHeaderPacket: packetCallback;
FieldPacket: packetCallback;
EofPacket: packetCallback;
RowDataPacket(packet: any, parser: any, connection: Connection): void;
/**
* Creates a Readable stream with the given options
*
* @param options The options for the stream. (see readable-stream package)
*/
stream(options?: stream.ReadableOptions): stream.Readable;
on(ev: string, callback: (...args: any[]) => void): Query;
on(ev: 'result', callback: (row: any, index: number) => void): Query;
on(ev: 'error', callback: (err: MysqlError) => void): Query;
on(ev: 'fields', callback: (fields: FieldInfo[], index: number) => void): Query;
on(ev: 'packet', callback: (packet: any) => void): Query;
on(ev: 'end', callback: () => void): Query;
}
export interface GeometryType extends Array<{ x: number, y: number } | GeometryType> {
x: number;
y: number;
}
export type TypeCast = boolean | (
(field: UntypedFieldInfo
& { type: string, length: number, string(): string, buffer(): Buffer, geometry(): null | GeometryType },
next: () => void) => any);
export type queryCallback = (err: MysqlError | null, results?: any, fields?: FieldInfo[]) => void;
// values can be non [], see custom format (https://github.com/mysqljs/mysql#custom-format)
export interface QueryFunction {
(query: Query): Query;
(options: string | QueryOptions, callback?: queryCallback): Query;
(options: string, values: any, callback?: queryCallback): Query;
}
export interface QueryOptions {
/**
* The SQL for the query
*/
sql: string;
/**
* Values for template query
*/
values?: any;
/**
* Every operation takes an optional inactivity timeout option. This allows you to specify appropriate timeouts for
* operations. It is important to note that these timeouts are not part of the MySQL protocol, and rather timeout
* operations through the client. This means that when a timeout is reached, the connection it occurred on will be
* destroyed and no further operations can be performed.
*/
timeout?: number;
/**
* Either a boolean or string. If true, tables will be nested objects. If string (e.g. '_'), tables will be
* nested as tableName_fieldName
*/
nestTables?: any;
/**
* Determines if column values should be converted to native JavaScript types. It is not recommended (and may go away / change in the future)
* to disable type casting, but you can currently do so on either the connection or query level. (Default: true)
*
* You can also specify a function (field: any, next: () => void) => {} to do the type casting yourself.
*
* WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once.
*
* field.string()
* field.buffer()
* field.geometry()
*
* are aliases for
*
* parser.parseLengthCodedString()
* parser.parseLengthCodedBuffer()
* parser.parseGeometryValue()
*
* You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast
*/
typeCast?: TypeCast;
}
export interface ConnectionOptions {
/**
* The MySQL user to authenticate as
*/
user?: string;