Finish restify typescript definition including its server and client api

This commit is contained in:
Bret Little
2013-02-14 13:46:32 -07:00
parent 204569719e
commit baa2dc5651
4 changed files with 336 additions and 350 deletions
-73
View File
@@ -1,73 +0,0 @@
/// <reference path="mongoose.d.ts" />
import mongoose = module("mongoose");
var mongoose2 = mongoose.Mongoose();
mongoose.connect('localhost', 'test').disconnect(()=>{});
mongoose.disconnect();
mongoose.set("key", "value").set("key", "value");
mongoose.get("key");
mongoose.model("model");
//@todo add tests for other model creation signatures
mongoose.plugin(()=>{}).plugin(()=>{}, {});
mongoose.exports.get("key");
//Connection Interface
var conn = new mongoose.Connection(mongoose2);
conn.open("test").open("test2", "db", 3, {}, ()=>{});
conn.openSet("test").openSet("test2", "db", {t: 3}, ()=>{});
conn.close().close(()=>{});
conn.collection("test");
conn.collection("test", {});
conn.model("test");
conn.setProfiling("0", 50);
conn.db;
conn.collections.test;
conn.readyState;
//Document Interface
//Model Interface
var model = mongoose.model("model");
model.save().save(()=>{});
model.increment().increment();
model.remove().remove(()=>{});
model.model("test").save();
model.$where('this.comments.length &gt; 5');
model.$where(()=>{});
model.ensureIndexes();
model.ensureIndexes(()=>{});
model.remove({title: ""});
model.remove({title: ""}, ()=>{});
model.find({ name: 'john', age: { $gte: 18 }});
model.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
model.findById("", 'name', { lean: true }, function (err, doc) {});
model.findById("", function (err, adventure) {});
model.findOne({ type: 'iphone' }, 'name', { lean: true }, ()=>{});
model.count({ type: 'jungle' }, function (err, count) {});
model.count({ type: 'test'});
model.distinct("test");
model.distinct("test", {}, ()=>{});
model.where('test');
model.where('test', {});
model.findOneAndUpdate({ name: 'test'}, { name: 'jason borne' }, {}, ()=>{});
model.findByIdAndUpdate("", { name: 'jason borne' }, {}, ()=>{});
model.findOneAndRemove({val: "test"});
model.findOneAndRemove({val: "tst"}, {}, ()=>{});
model.findByIdAndRemove("");
model.findByIdAndRemove("", {}, ()=>{});
model.create({ type: 'test' }, { type: 'test2' }, ()=>{});
model.create([{ type: 'test' }, { type: 'test2' }], ()=>{});
model.update({test: "test"}, {test: "tst2"});
model.update({test: "test"}, {test: "tst2"}, {safe: true, upsert: false}, ()=>{});
model.mapReduce({}, ()=>{});
model.aggregate([]);
model.aggregate([], {}, ()=>{});
model.base.get("key");
model.schema;
model.collection;
model.db;
-254
View File
@@ -1,254 +0,0 @@
interface MongooseInstance {
new(): MongooseInstance;
set(key: string, value: string) : MongooseInstance;
get(key: string) : string;
createConnection(uri?: string, options?: any) : MongooseInstance;
connect(...args: any[]) : MongooseInstance;
disconnect(fn?: Function) : MongooseInstance;
model(name: string, schema?: Schema, collection?: string, skipInit?: bool): Model;
plugin(fn: Function, opts?: any): MongooseInstance;
exports: MongooseInstance;
Collection: Collection;
Connection: Connection;
version() : string;
}
interface QueryOptions {
tailable?: any;
sort?: any;
limit?: any;
skip?: any;
maxscan?: any;
batchSize?: any;
comment?: any;
snapshot?: any;
hint?: any;
slaveOk?: any;
lean?: any;
safe?: any;
}
interface Query {
new(criteria: Object, options?: Object): Query;
setOptions(options: QueryOptions): Query;
exec(operation?: String, callback?: Function): Promise;
exec(operation?: Function, callback?: Function): Promise;
find(criteria?: Object, callback?: Function): Query;
cast(model: Model, obj?: Object): Object;
$where(js: string): Query;
$where(js: Function): Query;
where(path?: string, val?: Object): Query;
equals(val: Object): Query;
or(array: Array): Query;
nor(array: Array): Query;
and(array: Array): Query;
gt(path: string, val: number): Query;
gte(path: string, val: number): Query;
lt(path: string, val: number): Query;
lte(path: string, val: number): Query;
ne(path: string, val: number): Query;
in(path: string, val: number): Query;
nin(path: string, val: number): Query;
all(path: string, val: number): Query;
size(path: string, val: number): Query;
regex(path: string, val: number): Query;
maxDistance(path: string, val: number): Query;
near(path: string, val: number): Query;
nearSphere(path: string, val: Object): Query;
mod(path: string, val: number): Query;
exists(path: string, val: number): Query;
elemMatch(path: any, val: any): Query;
box(path: string, val: Object): Query;
center(path: string, val: Object, opts?: Object): Query;
centerSphere(path: string, val: Object): Query;
polygon(path: string, val: Array): Query;
polygon(path: string, val: Object): Query;
select(arg: Object): Query;
select(arg: string): Query;
slice(path: string, val: number): Query;
sort(arg: Object): Query;
sort(arg: String): Query;
limit(val: number): Query;
skip(val: number): Query;
maxscan(val: number): Query;
batchSize(val: number): Query;
comment(val: number): Query;
snapShot(): Query;
hint(val: Object): Query;
slaveOk(v: bool): Query;
read(pref: string, tags?: Array): Query;
lean(v: bool): Query;
tailable(v: bool): Query;
findOne(callback: Function): Query;
count(callback: Function): Query;
distinct( field: string, callback: Function): Query;
update(doc: Object, callback: Function): Query;
remove(callback: Function): Query;
findOneAndUpdate(query?: Object, doc?: Object, options?: findAndUpdateOptions, callback?: Function): Query;
findOneAndRemove(conditions?: Object, options?: findAndModifyOptions, callback?: Function): Query;
populate(path: string, fields?: Object, model?: Model, conditions?: Object, options?: Object): Query;
populate(path: string, fields?: string, model?: Model, conditions?: Object, options?: Object): Query;
stream(): QueryStream;
within: Query;
}
interface QueryStream {
new(query: Query): QueryStream;
pause();
resume();
destroy(err: any);
pipe();
paused: bool;
readable: bool;
}
interface findAndModifyOptions {
sort?: bool;
select?: bool;
}
interface findAndUpdateOptions extends findAndModifyOptions {
new?: bool;
upsert?: bool;
}
interface updateOptions {
safe?: bool;
upsert?: bool;
multi?: bool;
}
interface Model {
new(doc: any): Model;
save(fn?: Function);
increment(): Model;
remove(fn?: Function): Model;
model(name: string) : Model;
$where(argument: string): Query;
$where(argument: Function): Query;
ensureIndexes(cb?: Function): void;
remove(conditions: Object, callback?: Function): Query;
find(conditions: Object, fields?: Object, options?: Object, callback?: Function): Query;
findById(id: any, fields?: Object, options?: Object, callback?: Function): Query;
findOne(conditions: Object, fields?: Object, options?: Object, callback?: Function): Query;
count(conditions: Object, callback?: Function): Query;
distinct(field: string, conditions?: Object, callback?: Function): Query;
where(path: string, val?: Object): Query;
findOneAndUpdate(conditions?: Object, update?: Object, options?: findAndUpdateOptions, callback?: Function): Query;
findByIdAndUpdate(id: any, update?: Object, options?: findAndUpdateOptions, callback?: Function): Query;
findOneAndRemove(conditions: Object, options?: findAndModifyOptions, callback?: Function): Query;
findByIdAndRemove(id: any, options?: findAndModifyOptions, callback?: Function): Query;
create(doc: Array, callback: Function);
create(...args: any[]);
update(conditions: Object, update: Object, options?: updateOptions, callback?: Function): Query;
mapReduce(o: Object, callback: Function);
aggregate(array: Array, options?: Object, callback?: Function);
base: MongooseInstance;
schema: Schema;
modelName: string;
collection: Collection;
db: any;
}
interface DocumentToObjectSettings {
getters ?: bool;
virtuals ?: bool;
minimize ?: bool;
transform ?: Function ;
}
interface Document {
new(): Document;
update(doc: Object, options: Object, callback: Function);
set(path: any, val: any, type?: any, options?: Object): Document;
get(path: string, type: any): any;
markModified(path: string): void;
modifiedPaths(): Array;
isModified(path?: string): bool;
isDirectModified(path: string): bool;
isInit(path: string) :bool;
isSelected(path: string): bool;
validate(db: Function): Document;
invalidate(path: string, err: any): void;
toObject(options?: DocumentToObjectSettings): any;
toJSON(options) : any;
inspect(options?: any);
toString();
equals(doc: Document): bool;
errors: Object;
id: string;
isNew: bool;
schema: Schema;
}
interface Schema {
Types: {
String: any;
Number: any;
Boolean: any;
Bool: any;
Array: any;
Buffer: any;
Date: any;
ObjectId: any;
Oid: any;
Mixed: any;
};
}
interface Promise {
new(back: Function): Promise;
on(event: string, callback: Function): Promise;
complete();
error(): Promise;
addCallback(fn: Function): Promise;
addErrback(fn: Function): Promise;
addBack(fn: Function): Promise;
resolve(err?: any, val?: Object);
}
interface SchemaType {
}
interface Collection {
}
interface Connection {
new(base: MongooseInstance) : Connection;
open(connection_string: string, database?: string, port?: number, options?: Object, callback?: Function): Connection;
openSet(urlis: string, database?: string, options?: Object, callback?: Function): Connection;
close(callback?:Function): Connection;
collection(name: string, options?: Object): Collection;
model(name: string, schema?: Schema, collection?: Collection): Model;
setProfiling(level: any, ms?: number, callback?: Function): void;
db: any;
collections: any;
readyState: number;
}
interface CheerioStatic {
// (...selectors: any[]): Cheerio;
// (): Cheerio;
}
declare module "mongoose" {
export function Mongoose(): MongooseInstance;
export function set(key: string, value: string) : MongooseInstance;
export function get(key: string) : string;
export function createConnection(uri?: string, options?: any): MongooseInstance;
export function connect(...args: any[]): MongooseInstance;
export function disconnect(fn?: Function): MongooseInstance;
export function model(name: string, schema?: Schema, collection?: string, skipInit?: bool): Model;
export function plugin(fn: Function, opts?: any): MongooseInstance;
export var exports : MongooseInstance;
export var Collection : Collection;
export var Connection : Connection;
export function version() : string;
export var Schema : Schema;
export var SchemaType: SchemaType;
}
+201
View File
@@ -15,3 +15,204 @@ var server = restify.createServer({
}
}
});
server = restify.createServer({
certificate: "test",
key: "test",
formatters: {},
log: {},
name: "test",
spdy: {},
version: "",
responseTimeHeader: "",
responseTimeFormatter : (durationInMilliseconds: number) => {}
});
server.on('someEvent', ()=>{});
server.use((req, res, next)=>{});
server.use([(req, res, next)=>{}]);
server.use((req, res, next)=>{}, (req, res, next)=>{});
function send(req, res, next) {
req.header('key', 'val');
req.header('key') === 'val';
req.accepts('test') === true;
req.is('test') === true;
req.getLogger('test');
var log = req.log;
log.debug({params: req.params}, 'Hello there %s', 'foo');
req.contentLength === 50;
req.contentType === 'test';
req.href === 'test';
req.id === 'test';
req.path === 'test';
req.query === 'test';
req.secure === true;
req.time === 50;
req.params;
res.header('test');
res.header('test', {});
res.header('test', new Date());
res.cache();
res.cache('testst', {});
res.status(344);
res.send({hello: 'world'});
res.send(201, {hello: 'world'});
res.send(new restify.BadRequestError('meh'));
res.json(201, {hello: 'world'});
res.json({hello: 'world'});
res.code === 50;
res.contentLength === 50;
res.charSet === 'test';
res.contentType === 'test';
res.headers;
res.id === 'test';
res.send('hello ' + req.params.name);
return next();
}
server.post('/hello', send);
server.put( '/hello', send);
server.del( '/hello', send);
server.get( '/hello', send);
server.head('/hello', send);
server.post(/(.*)/, send);
server.put( /(.*)/, send);
server.del( /(.*)/, send);
server.get( /(.*)/, send);
server.head(/(.*)/, send);
new restify.ConflictError("test");
new restify.InvalidArguementError("message");
new restify.RestError("message");
new restify.BadDigestError("message");
new restify.BadMethodError("message");
new restify.BadRequestError('test');
new restify.InternalError("message");
new restify.InvalidContentError("message");
new restify.InvalidCredentialsError("message");
new restify.InvalidHeaderError("message");
new restify.InvalidVersionError("message");
new restify.MissingParameterError("message");
new restify.NotAuthorizedError("message");
new restify.RequestExpiredError("jjmessage");
new restify.RequestThrottledError("message");
new restify.ResourceNotFoundError("message");
new restify.WrongAcceptError("message");
server.name = "";
server.version = "";
server.log = {};
server.acceptable = ["test"];
server.url = "";
server.address().port;
server.address().family;
server.address().address;
server.listen("somePath", send);
server.close();
server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.jsonp());
server.use(restify.gzipResponse());
server.use(restify.bodyParser());
server.use(restify.throttle({
burst: 100,
rate: 50,
ip: true,
overrides: {
'192.168.1.1': {
rate: 0,
burst: 0
}
}
}));
server.on('after', restify.auditLogger({
log: ()=>{}
}));
restify.defaultResponseHeaders = function(data) {
this.header('Server', 'helloworld');
};
restify.defaultResponseHeaders = false;
//RESTIFY Client Tests
var client = restify.createJsonClient({
url: 'https://api.us-west-1.joyentcloud.com',
version: '*'
});
client = restify.createStringClient({
accept: "test",
connectTimeout: 30,
dtrace: {},
gzip: {},
headers: {},
log: {},
retry: {},
signRequest: ()=>{},
url: "",
userAgent: "",
version: ""
});
client.get("test", send);
client.head('test', send);
client.post('path', {}, send);
client.put('path', {}, send);
client.del('path', send);
client.post('/foo', { hello: 'world' }, function(err, req, res, obj) {
console.log('%d -> %j', res.statusCode, res.headers);
console.log('%j', obj);
});
client.get('/foo/bar', function(err, req, res, data) {
console.log('%s', data);
});
var client2 = restify.createClient({
url: 'http://127.0.0.1'
});
client2.get('/str/mcavage', function(err, req) {
req.on('result', function(err, res) {
res.body = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
res.body += chunk;
});
res.on('end', function() {
console.log(res.body);
});
});
});
client.basicAuth('test', 'password');
client2.basicAuth('test', 'password');
+135 -23
View File
@@ -1,10 +1,59 @@
interface addressInterface {
port: number;
family: string;
address: string;
}
interface Request {
header: (key: string, defaultValue?: string) => any;
accepts: (type: string) => bool;
is: (type: string) => bool;
getLogger: (component: string) => any;
contentLength: number;
contentType: string;
href: string;
log: Object;
id: string;
path: string;
query: string;
secure: bool;
time: number;
params: any;
}
interface Response {
header: (key: string, value ?: any) => any;
cache: (type?: any, options?: Object) => any;
status: (code: number) => any;
send: (status?: any, body?: any) => any;
json: (status?: any, body?: any) => any;
code: number;
contentLength: number;
charSet: string;
contentType: string;
headers: Object;
statusCode: number;
id: string;
}
interface Server {
use: (... handler: any[]) => any;
post: (route: any, routeCallBack: (req: any, res: any, next: any) => any) => any;
put: (route: any, routeCallBack: (req: any, res: any, next: any) => any) => any;
del: (route: any, routeCallBack: (req: any, res: any, next: any) => any) => any;
get: (route: any, routeCallBack: (req: any, res: any, next: any) => any) => any;
head: (route: any, routeCallBack: (req: any, res: any, next: any) => any) => any;
post: (route: any, routeCallBack: (req: Request, res: Response, next: Function) => any) => any;
put: (route: any, routeCallBack: (req: Request, res: Response, next: Function) => any) => any;
del: (route: any, routeCallBack: (req: Request, res: Response, next: Function) => any) => any;
get: (route: any, routeCallBack: (req: Request, res: Response, next: Function ) => any) => any;
head: (route: any, routeCallBack: (req: Request, res: Response, next: Function) => any) => any;
on: (event: string, callback: Function) => any;
name: string;
version: string;
log: Object;
acceptable: string[];
url: string;
address: () => addressInterface;
listen: (... args: any[]) => any;
close: (... args: any[]) => any;
pre: (routeCallBack: (req: Request, res: Response, next: Function) => any) => any;
}
interface ServerOptions {
@@ -15,26 +64,89 @@ interface ServerOptions {
name ?: string;
spdy ?: Object;
version ?: string;
responseTimerHeader ?: string;
responseTimeHeader ?: string;
responseTimeFormatter ?: (durationInMilliseconds: number) => any;
}
interface ClientOptions {
accept?: string;
connectTimeout?: number;
dtrace?: Object;
gzip?: Object;
headers?: Object;
log?: Object;
retry?: Object;
signRequest?: Function;
url?: string;
userAgent?: string;
version?: string;
}
interface Client {
get: (path: string, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any;
head: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any;
post: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any;
put: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any;
del: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any;
basicAuth: (username: string, password: string) => any;
}
interface HttpClient extends Client {
get: (path?: any, callback?: Function) => any;
head: (path?:any, callback?: Function) => any;
post: (opts?: any, callback?: Function) => any;
put: (opts?: any, callback?: Function) => any;
del: (opts?: any, callback?: Function) => any;
}
interface ThrottleOptions {
burst?: number;
rate?: number;
ip?: bool;
xff?: bool;
username?: bool;
tokensTable?: Object;
maxKeys?: number;
overrides?: Object;
}
declare module "restify" {
export function createServer(options: ServerOptions): Server;
export class ConflictError { new(message: any): ConflictError; };
export class InvalidArguementError { new(message: any): InvalidArguementError; };
export class RestError { new(message: any): RestError; };
export class BadDigestError { new(message: any): BadDigestError; };
export class BadMethodError { new(message: any): BadMethodError; };
export class InternalError { new(message: any): InternalError; };
export class InvalidContentError { new(message: any): InvalidContentError; };
export class InvalidCredentialsError { new(message: any): InvalidCredentialsError; };
export class InvalidHeaderError { new(message: any): InvalidHeaderError; };
export class InvalidVersionError { new(message: any): InvalidVersionError; };
export class MissingParameterError { new(message: any): MissingParameterError; };
export class NotAuthorizedError { new(message: any): NotAuthorizedError; };
export class RequestExpiredError { new(message: any): RequestExpiredError; };
export class RequestThrottledError { new(message: any): RequestThrottledError; };
export class ResourceNotFoundError { new(message: any): ResourceNotFoundError; };
export class WrongAcceptError { new(message: any): WrongAcceptError; };
export function createServer(options?: ServerOptions): Server;
export function createJsonClient(options?: ClientOptions): Client;
export function createStringClient(options?: ClientOptions): Client;
export function createClient(options?: ClientOptions): HttpClient;
export class ConflictError { constructor(message?: any); };
export class InvalidArguementError { constructor(message?: any); };
export class RestError { constructor(message?: any); };
export class BadDigestError { constructor(message: any); };
export class BadMethodError { constructor(message: any); };
export class BadRequestError { constructor(message: any); };
export class InternalError { constructor(message: any); };
export class InvalidContentError { constructor(message: any); };
export class InvalidCredentialsError { constructor(message: any); };
export class InvalidHeaderError { constructor(message: any); };
export class InvalidVersionError { constructor(message: any); };
export class MissingParameterError { constructor(message: any); };
export class NotAuthorizedError { constructor(message: any); };
export class RequestExpiredError { constructor(message: any); };
export class RequestThrottledError { constructor(message: any); };
export class ResourceNotFoundError { constructor(message: any); };
export class WrongAcceptError { constructor(message: any); };
export function acceptParser(parser: any);
export function authorizationParser();
export function dateParser(skew?: number);
export function queryParser(options?: Object);
export function urlEncodedBodyParser(options?: Object);
export function jsonp(options?: Object);
export function gzipResponse(options?: Object);
export function bodyParser(options?: Object);
export function requestLogger(options?: Object);
export function serveStatic(options?: Object);
export function throttle(options?: ThrottleOptions);
export function conditionalRequest(options?: Object);
export function auditLogger(options?: Object);
export var defaultResponseHeaders : any;
}