Merge pull request #6776 from reppners/js-data

typings and tests for js-data 2.8.0, making use of new typescript int…
This commit is contained in:
Masahiro Wakame
2015-11-17 00:09:26 +09:00
9 changed files with 1214 additions and 201 deletions
+5 -9
View File
@@ -13,16 +13,12 @@ declare module JSData {
}
interface DS {
bindAll<T>(resourceName:string, params:DSFilterParams, scope:ng.IScope, expr:string, cb?:(err:DSError, items:Array<T>)=>void):Function;
bindOne<T>(resourceName:string, id:string | number, scope:ng.IScope, expr:string, cb?:(err:DSError, item:T)=>void):Function;
bindAll<T>(resourceName:string, params:DSFilterParams, scope:ng.IScope, expr:string, cb?:(err:DSError, items:Array<T & DSInstanceShorthands<T>>)=>void):Function;
bindOne<T>(resourceName:string, id:string | number, scope:ng.IScope, expr:string, cb?:(err:DSError, item:T & DSInstanceShorthands<T>)=>void):Function;
}
interface DSResourceDefinition<T> {
bindAll<T>(params:DSFilterParams, scope:ng.IScope, expr:string, cb?:(err:DSError, items:Array<T>)=>void):Function;
bindOne<T>(id:string | number, scope:ng.IScope, expr:string, cb?:(err:DSError, item:T)=>void):Function;
bindAll(params:DSFilterParams, scope:ng.IScope, expr:string, cb?:(err:DSError, items:Array<T & DSInstanceShorthands<T>>)=>void):Function;
bindOne(id:string | number, scope:ng.IScope, expr:string, cb?:(err:DSError, item:T & DSInstanceShorthands<T>)=>void):Function;
}
}
}
+2 -2
View File
@@ -28,7 +28,7 @@ ADocument.inject({ id: 5, author: 'John' });
ADocument.inject({ id: 6, author: 'John' });
// bypass the data store
adapter.updateAll<{ id?: number; author: string; }>(ADocument, { author: 'Johnny' }, { author: 'John' }).then(function (documents) {
adapter.updateAll(ADocument, { author: 'Johnny' }, { author: 'John' }).then(function (documents) {
documents[0]; // { id: 5, author: 'Johnny' }
// The updated documents have NOT been injected into the data store because we bypassed the data store
@@ -37,7 +37,7 @@ adapter.updateAll<{ id?: number; author: string; }>(ADocument, { author: 'Johnny
});
// Normally you would just go through the data store
ADocument.updateAll<{ id?: number; author: string; }>({ author: 'Johnny' }, { author: 'John' }).then(function (documents) {
ADocument.updateAll({ author: 'Johnny' }, { author: 'John' }).then(function (documents) {
documents[0]; // { id: 5, author: 'Johnny' }
// the updated documents have been injected into the data store
+6 -2
View File
@@ -6,7 +6,7 @@
/// <reference path="../js-data/js-data.d.ts" />
declare module JSData {
interface DSHttpAdapterOptions {
serialize?: (resourceName:string, data:any)=>any;
deserialize?: (resourceName:string, data:any)=>any;
@@ -37,4 +37,8 @@ declare module JSData {
}
}
declare var DSHttpAdapter:JSData.DSHttpAdapter;
declare var DSHttpAdapter:JSData.DSHttpAdapter;
declare module 'js-data-http' {
export = DSHttpAdapter;
}
+4 -6
View File
@@ -1,17 +1,15 @@
/// <reference path="js-data.d.ts" />
/// <reference path="../js-data-http/js-data-http.d.ts" />
import JSData = require('js-data');
//TODO
//import DSRedisAdapter = require('js-data-redis')
import DSHttpAdapter = require('js-data-http')
var store = new JSData.DS();
// register and use http by default for async operations
//TODO
//store.registerAdapter('redis', new DSRedisAdapter(), {default: true});
store.registerAdapter('redis', new DSHttpAdapter(), {default: true});
// simplest model definition
var User = store.defineResource('user');
User.find(1).then(function (user: any) {
user; // { id: 1, name: 'John' }
});
});
+78 -20
View File
@@ -11,7 +11,7 @@ interface IUser {
}
interface IUserWithMethod extends IUser {
fullName?: () => string;
fullName:()=>string;
}
interface IUserWithComputedProperty extends IUser {
@@ -20,10 +20,6 @@ interface IUserWithComputedProperty extends IUser {
var store = new JSData.DS();
// register and use http by default for async operations
//TODO
//store.registerAdapter('http', new DSHttpAdapter(), {default: true});
// simplest model definition
var User = store.defineResource<IUser>('user');
@@ -31,12 +27,12 @@ User.find(1).then(function (user:IUser) {
user; // { id: 1, name: 'John' }
});
var user:IUser = User.createInstance<IUser>({name: 'John'});
var user:IUser = User.createInstance({name: 'John'});
var store = new JSData.DS();
var User = store.defineResource('user');
var user:IUser = User.inject<IUser>({id: 1, name: 'John'});
var user2:IUser = User.inject<IUser>({id: 1, age: 30});
var User2 = store.defineResource('user');
var user:IUser = User2.inject({id: 1, name: 'John'});
var user2:IUser = User2.inject({id: 1, age: 30});
user; // User { id: 1, name: 'John', age: 30 }
user2; // User { id: 1, name: 'John', age: 30 }
@@ -70,7 +66,7 @@ User.create({
var store = new JSData.DS();
var UserWithMethod = store.defineResource<IUserWithMethod>({
var UserWithMethodResource = store.defineResource<IUserWithMethod>({
name: 'user',
methods: {
fullName: function () {
@@ -79,7 +75,7 @@ var UserWithMethod = store.defineResource<IUserWithMethod>({
}
});
var userWithMethod = UserWithMethod.createInstance<IUserWithMethod>({first: 'John', last: 'Anderson'});
var userWithMethod = UserWithMethodResource.createInstance({first: 'John', last: 'Anderson'});
userWithMethod.fullName(); // "John Anderson"
@@ -102,7 +98,7 @@ var UserWithComputedProperty = store.defineResource<IUserWithComputedProperty>({
}
});
var userWithComputedProperty:IUserWithComputedProperty = UserWithComputedProperty.inject<IUserWithComputedProperty>({
var userWithComputedProperty:IUserWithComputedProperty = UserWithComputedProperty.inject({
id: 1,
first: 'John',
last: 'Anderson'
@@ -284,7 +280,7 @@ Post.filter({
limit: PAGE_SIZE
});
var User = store.defineResource({
var User3 = store.defineResource({
name: 'user',
relations: {
hasMany: {
@@ -362,7 +358,7 @@ User.find(10).then(function (user:IUser) {
user.comments; // undefined
user.profile; // undefined
User.loadRelations(user, ['comment', 'profile']).then(function (user:IUser) {
User.loadRelations(user.id, ['comment', 'profile']).then(function (user:IUser) {
user.comments; // array
user.profile; // object
});
@@ -403,24 +399,24 @@ OtherOtherComment.update(1, {content: 'stuff'}, {params: {postId: false}}); // P
var store = new JSData.DS({
// set the default
beforeCreate: function (resource, data, cb) {
beforeCreate: function (resource:JSData.DSResourceDefinition<any>, data:any, cb:(err:Error, returnData:any)=>void) {
// do something general
cb(null, data);
}
});
var User = store.defineResource({
var User4 = store.defineResource({
name: 'user',
// set just for this resource
beforeCreate: function (resource, data, cb) {
beforeCreate: function (resource:JSData.DSResourceDefinition<any>, data:any, cb:(err:Error, returnData:any)=>void) {
// do something more specific to "users"
cb(null, data);
}
});
User.create({name: 'John'}, {
User4.create({name: 'John'}, {
// set just for this method call
beforeCreate: function (resource, data, cb) {
beforeCreate: function (resource:JSData.DSResourceDefinition<any>, data:any, cb:(err:Error, returnData:any)=>void) {
// do something specific for this method call
cb(null, data);
}
@@ -521,4 +517,66 @@ var store = new JSData.DS();
var myResourceDefinition = store.defineResource<MyResourceDefinition>('myResource');
myResourceDefinition = store.definitions.myResource;
myResourceDefinition = store.definitions.myResource;
/**
* Custom action on datastore resource
*/
interface Resource {
someProp:string;
}
interface ActionsForResource {
myAction:JSData.DSActionFn;
myOtherAction:JSData.DSActionFn;
}
var myOtherAction:JSData.DSActionConfig = {
method: 'GET',
endpoint: 'goHere'
};
var customActionResource = store.defineResource<Resource, ActionsForResource>({
name: 'actionResource',
actions: {
myAction: {
method: 'POST'
},
myOtherAction: myOtherAction
}
});
customActionResource.myAction<number>(3).then((result)=>{
var theCustomResult:number = result;
});
customActionResource.myOtherAction<void>(2, {data:'blub'}).then(()=>{
// success
});
customActionResource.find(1).then((result)=>{
var aProperty = result.someProp;
});
/**
* Instance shorthands
*/
var customActionResourceInstance = customActionResource.get(1);
customActionResourceInstance.DSCompute();
customActionResourceInstance.DSChanges();
customActionResourceInstance.DSChangeHistory();
customActionResourceInstance.DSHasChanges();
customActionResourceInstance.DSLastModified();
customActionResourceInstance.DSLastSaved();
customActionResourceInstance.DSPrevious();
customActionResourceInstance.DSCreate();
customActionResourceInstance.DSDestroy();
customActionResourceInstance.DSLoadRelations('myRelation');
customActionResourceInstance.DSRefresh();
customActionResourceInstance.DSSave();
customActionResourceInstance.DSUpdate();
+206 -162
View File
@@ -1,4 +1,4 @@
// Type definitions for JSData v1.5.4
// Type definitions for JSData v2.8.0
// Project: https://github.com/js-data/js-data
// Definitions by: Stefan Steinhart <https://github.com/reppners>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -7,135 +7,66 @@
// js-data module (js-data.js)
///////////////////////////////////////////////////////////////////////////////
// defining what exists in JSData and how it looks
declare module JSData {
interface JSDataPromise<R> {
then<U>(onFulfilled?:(value:R) => U | JSDataPromise<U>, onRejected?:(error:any) => U | JSDataPromise<U>): JSDataPromise<U>;
then<U>(onFulfilled?: (value: R) => U | JSDataPromise<U>, onRejected?: (error: any) => U | JSDataPromise<U>): JSDataPromise<U>;
catch<U>(onRejected?: (error: any) => U | JSDataPromise<U>): JSDataPromise<U>;
catch<U>(onRejected?:(error:any) => U | JSDataPromise<U>): JSDataPromise<U>;
// enhanced with finally
finally<U>(finallyCb?:() => U):JSDataPromise<U>;
}
//TODO switch to class again when typescript supports open ended class declaration
interface DS {
new(config?:DSConfiguration):DS;
// rather undocumented
errors:DSErrors;
// those are objects containing the defined resources and adapters
definitions:any;
adapters:any;
defaults:DSConfiguration;
// async
create<T>(resourceName:string, attrs:Object, options?:DSConfiguration):JSDataPromise<T>;
destroy(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<any>;
destroyAll(resourceName:string, params?:DSFilterParams, options?:DSAdapterOperationConfiguration):JSDataPromise<any>;
find<T>(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T>;
findAll<T>(resourceName:string, params?:DSFilterParams, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T>>;
loadRelations<T>(resourceName:string, idOrInstance:string | number | Object, relations:string | Array<string>, options?:DSAdapterOperationConfiguration):JSDataPromise<T>;
update<T>(resourceName:string, id:string | number, attrs:Object, options?:DSSaveConfiguration):JSDataPromise<T>;
updateAll<T>(resourceName:string, attrs:Object, params?:DSFilterParams, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T>>;
reap(resourceName:string, options?:DSConfiguration):JSDataPromise<any>;
refresh<T>(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T>;
save<T>(resourceName:string, id:string | number, options?:DSSaveConfiguration):JSDataPromise<T>;
// sync
changeHistory(resourceName:string, id?:string | number):Array<Object>;
changes(resourceName:string, id:string | number):Object;
compute<T>(resourceName:string, idOrInstance:number | string | Object ):T;
createInstance<T>(resourceName:string, attrs?:T, options?:DSAdapterOperationConfiguration):T;
defineResource<T>(resourceNameOrDefinition:string | DSResourceDefinitionConfiguration):DSResourceDefinition<T>;
digest():void;
eject<T>(resourceName:string, id:string | number, options?:DSConfiguration):T;
ejectAll<T>(resourceName:string, params:DSFilterParams, options?:DSConfiguration):Array<T>;
filter<T>(resourceName:string, params:DSFilterParams, options?:DSConfiguration):Array<T>;
get<T>(resourceName:string, id:string | number, options?:DSConfiguration):T;
getAll<T>(resourceName:string, ids?:Array<string | number>):Array<T>;
hasChanges(resourceName:string, id:string | number):boolean;
inject<T>(resourceName:string, attrs:T, options?:DSConfiguration):T;
inject<T>(resourceName:string, items:Array<T>, options?:DSConfiguration):Array<T>;
is(resourceName:string, object:Object): boolean;
lastModified(resourceName:string, id?:string | number):number; // timestamp
lastSaved(resourceName:string, id?:string | number):number; // timestamp
link<T>(resourceName:string, id:string | number, relations?:Array<string>):T;
linkAll<T>(resourceName:string, params:DSFilterParams, relations?:Array<string>):T;
linkInverse<T>(resourceName:string, id:string | number, relations?:Array<string>):T;
previous<T>(resourceName:string, id:string | number):T;
unlinkInverse<T>(resourceName:string, id:string | number, relations?:Array<string>):T;
registerAdapter(adapterId:string, adapter:IDSAdapter, options?:{default: boolean}):void;
}
interface DSConfiguration extends IDSResourceLifecycleEventHandlers {
actions?: Object;
allowSimpleWhere?: boolean;
basePath?: string;
bypassCache?: boolean;
cacheResponse?: boolean;
clearEmptyQueries?:boolean;
debug?:boolean;
defaultAdapter?: string;
defaultFilter?: (collection:Array<any>, resourceName:string, params:DSFilterParams, options:DSConfiguration)=>Array<any>;
defaultFilter?: (collection:Array<any>, resourceName:string, params:DSFilterArg, options:DSConfiguration)=>Array<any>;
defaultValues?:Object;
eagerEject?: boolean;
// TODO enable when eagerInject in DS#create is implemented
//eagerInject?: boolean;
endpoint?: string;
error?: boolean | ((message?:any, ...optionalParams:any[])=> void);
fallbackAdapters?: Array<string>;
findAllFallbackAdapters?: Array<string>;
findAllStrategy?: string;
findBelongsTo?: boolean;
findFallbackAdapters?: Array<string>;
findHasOne?: boolean;
findHasMany?: boolean;
findInverseLinks?: boolean;
findStrategy?: string
findStrictCache?:boolean;
idAttribute?: string;
ignoredChanges?: Array<RegExp | string>;
// TODO ignoreMissing is undocumented
//ignoreMissing: boolean;
ignoreMissing?: boolean;
instanceEvents?:boolean;
keepChangeHistory?: boolean;
loadFromServer?: boolean;
log?: boolean | ((message?: any, ...optionalParams: any[])=> void);
linkRelations?:boolean;
log?: boolean | ((message?:any, ...optionalParams:any[])=> void);
maxAge?: number;
notify?: boolean;
omit?:Array<string|RegExp>;
onConflict?:string; // "merge"(default) or "replace"
reapAction?: string;
reapInterval?: number;
relationsEnumerable?:boolean;
resetHistoryOnInject?: boolean;
returnMeta?:boolean;
scopes?:Object;
strategy?: string;
upsert?: boolean;
useClass?: boolean;
useFilter?: boolean;
}
interface DSAdapterOperationConfiguration extends DSConfiguration {
adapter?: string;
bypassCache?: boolean;
cacheResponse?: boolean;
findStrategy?: string;
findFallbackAdapters?: string[];
strategy?: string;
fallbackAdapters?: string[];
params: {
[paramName: string]: string | number | boolean;
};
}
interface DSSaveConfiguration extends DSAdapterOperationConfiguration {
changesOnly?: boolean;
watchChanges?:boolean;
}
interface DSResourceDefinitionConfiguration extends DSConfiguration {
name: string;
computed?: any;
meta?:any;
methods?: any;
name: string;
relations?: {
hasMany?: Object;
hasOne?: Object;
@@ -143,46 +74,6 @@ declare module JSData {
};
}
interface DSResourceDefinition<T> extends DSResourceDefinitionConfiguration {
//async
create<T>(attrs:Object, options?:DSConfiguration):JSDataPromise<T>;
destroy(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<any>;
destroyAll(params?:DSFilterParams, options?:DSAdapterOperationConfiguration):JSDataPromise<any>;
find<T>(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T>;
findAll<T>(params?:DSFilterParams, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T>>;
loadRelations<T>(idOrInstance:string | number | Object, relations:string | Array<string>, options?:DSAdapterOperationConfiguration):JSDataPromise<T>;
update<T>(id:string | number, attrs:Object, options?:DSSaveConfiguration):JSDataPromise<T>;
updateAll<T>(attrs:Object, params?:DSFilterParams & T, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T>>;
reap(resourceNametions?:DSConfiguration):JSDataPromise<any>;
refresh<T>(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T>;
save<T>(id:string | number, options?:DSSaveConfiguration):JSDataPromise<T>;
// sync
changeHistory(id?:string | number):Array<Object>;
changes(id:string | number):Object;
compute<T>(idOrInstance:number | string | Object ):T;
createInstance<T>(attrs?:T, options?:DSAdapterOperationConfiguration):T;
digest():void;
eject<T>(id:string | number, options?:DSConfiguration):T;
ejectAll<T>(params:DSFilterParams, options?:DSConfiguration):Array<T>;
filter<T>(params: DSFilterParams, options?: DSConfiguration): Array<T>;
filter<T>(params: DSFilterParamsForAllowSimpleWhere, options?: DSConfiguration): Array<T>;
get<T>(id:string | number, options?:DSConfiguration):T;
getAll<T>(ids?:Array<string | number>):Array<T>;
hasChanges(id:string | number):boolean;
inject<T>(attrs:T, options?:DSConfiguration):T;
inject<T>(items:Array<T>, options?:DSConfiguration):Array<T>;
is(object:Object): boolean;
lastModified(id?:string | number):number; // timestamp
lastSaved(id?:string | number):number; // timestamp
link<T>(id:string | number, relations?:Array<string>):T;
linkAll<T>(params:DSFilterParams, relations?:Array<string>):T;
linkInverse<T>(id:string | number, relations?:Array<string>):T;
previous<T>(id:string | number):T;
unlinkInverse<T>(id:string | number, relations?:Array<string>):T;
}
interface DSFilterParams {
where?: Object;
@@ -195,49 +86,188 @@ declare module JSData {
sort?: string | Array<string> | Array<Array<string>>;
}
interface DSFilterParamsForAllowSimpleWhere {
[key: string]: string | number;
type DSFilterArg = DSFilterParams | Object;
interface DSAdapterOperationConfiguration extends DSConfiguration {
adapter?: string;
params?: {
[paramName: string]: string | number | boolean;
};
}
interface DSSaveConfiguration extends DSAdapterOperationConfiguration {
changesOnly?: boolean;
}
interface DSCollection<T> extends Array<T> {
fetch(params?:DSFilterArg, options?:DSConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
params:DSFilterArg;
resourceName:string;
}
interface DS {
new(config?:DSConfiguration):DS;
// rather undocumented
errors:DSErrors;
// those are objects containing the defined resources and adapters
definitions:any;
adapters:any;
defaults:DSConfiguration;
changeHistory(resourceName:string, id:string | number):Array<Object>;
changes(resourceName:string, id:string | number, options?:{ignoredChanges:Array<string|RegExp>}):Object;
clear<T>():Array<T & DSInstanceShorthands<T>>;
compute<T>(resourceName:string, idOrInstance:number | string | T):T & DSInstanceShorthands<T>;
create<T>(resourceName:string, attrs:Object, options?:DSConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
createCollection<T>(resourceName:string, array?:Array<T>, params?:DSFilterArg, options?:DSConfiguration):DSCollection<T & DSInstanceShorthands<T>>;
createInstance<T>(resourceName:string, attrs?:Object, options?:DSConfiguration):T & DSInstanceShorthands<T>;
destroy(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<void>;
destroyAll(resourceName:string, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<void>;
digest():void;
eject<T>(resourceName:string, id:string | number, options?:DSConfiguration):T & DSInstanceShorthands<T>;
ejectAll<T>(resourceName:string, params:DSFilterArg, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
filter<T>(resourceName:string, params:DSFilterArg, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
find<T>(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
findAll<T>(resourceName:string, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
get<T>(resourceName:string, id:string | number):T & DSInstanceShorthands<T>;
getAll<T>(resourceName:string, ids?:Array<string | number>):Array<T & DSInstanceShorthands<T>>;
hasChanges(resourceName:string, id:string | number):boolean;
inject<TInject, U>(resourceName:string, attrs:TInject, options?:DSConfiguration):U & DSInstanceShorthands<U>;
inject<TInject, U>(resourceName:string, items:Array<TInject>, options?:DSConfiguration):Array<U & DSInstanceShorthands<U>>;
is(resourceName:string, object:Object): boolean;
lastModified(resourceName:string, id?:string | number):number; // timestamp
lastSaved(resourceName:string, id?:string | number):number; // timestamp
loadRelations<T>(resourceName:string, idOrInstance:string | number, relations:string | Array<string>, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
previous<T>(resourceName:string, id:string | number):T & DSInstanceShorthands<T>;
reap(resourceName:string):JSDataPromise<void>;
refresh<T>(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
refreshAll<T>(resourceName:string, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
revert<T>(resourceName:string, id:string | number):T & DSInstanceShorthands<T>;
save<T>(resourceName:string, id:string | number, options?:DSSaveConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
update<T>(resourceName:string, id:string | number, attrs:Object, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
updateAll<T>(resourceName:string, attrs:Object, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
defineResource<T>(resourceNameOrDefinition:string | DSResourceDefinitionConfiguration):DSResourceDefinition<T>;
defineResource<T, TActions>(resourceNameOrDefinition:string | DSResourceDefinitionConfiguration):DSResourceDefinition<T> & TActions;
registerAdapter(adapterId:string, adapter:IDSAdapter, options?:{default: boolean}):void;
}
interface DSResourceDefinition<T> extends DSResourceDefinitionConfiguration {
changeHistory(id:string | number):Array<Object>;
changes(id:string | number, options?:{ignoredChanges:Array<string|RegExp>}):Object;
clear():Array<T & DSInstanceShorthands<T>>;
compute(idOrInstance:number | string | T):T & DSInstanceShorthands<T>;
create(attrs:Object, options?:DSConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
createCollection(array?:Array<T>, params?:DSFilterArg, options?:DSConfiguration):DSCollection<T & DSInstanceShorthands<T>>;
createInstance(attrs?:Object, options?:DSConfiguration):T & DSInstanceShorthands<T>;
destroy(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<void>;
destroyAll(params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<void>;
digest():void;
eject(id:string | number, options?:DSConfiguration):T & DSInstanceShorthands<T>;
ejectAll(params:DSFilterArg, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
filter(params:DSFilterArg, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
find(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
findAll(params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
get(id:string | number):T & DSInstanceShorthands<T>;
getAll(ids?:Array<string | number>):Array<T & DSInstanceShorthands<T>>;
hasChanges(id:string | number):boolean;
inject<TInject>(attrs:TInject, options?:DSConfiguration):T & DSInstanceShorthands<T>;
inject<TInject>(items:Array<TInject>, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
is(object:Object): boolean;
lastModified(id?:string | number):number; // timestamp
lastSaved(id?:string | number):number; // timestamp
loadRelations(idOrInstance:string | number, relations:string | Array<string>, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
previous(id:string | number):T & DSInstanceShorthands<T>;
reap():JSDataPromise<void>;
refresh(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
refreshAll(params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
revert(id:string | number):T & DSInstanceShorthands<T>;
save(id:string | number, options?:DSSaveConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
update(id:string | number, attrs:Object, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
updateAll(attrs:Object, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
}
// cannot specify T at interface level because the interface is used as generic constraint itself which ends up being recursive
export interface DSInstanceShorthands<T> {
DSCompute():void;
DSRefresh(options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSSave(options?:DSSaveConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSUpdate(options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSDestroy(options?:DSAdapterOperationConfiguration):JSDataPromise<void>;
DSCreate(options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSLoadRelations(relations:string | Array<string>, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSChangeHistory():Array<Object>;
DSChanges():Object;
DSHasChanges():boolean;
DSLastModified():number; // timestamp
DSLastSaved():number; // timestamp
DSPrevious():T & DSInstanceShorthands<T>;
DSRevert():T & DSInstanceShorthands<T>;
}
type DSSyncLifecycleHookHandler = (resource:DSResourceDefinition<any>, data:any) => void;
type DSAsyncLifecycleHookHandler = (resource:DSResourceDefinition<any>, data:any) => JSDataPromise<any>;
type DSAsyncLifecycleHookHandlerCb = (resource:DSResourceDefinition<any>, data:any, cb:(err:Error, data:any)=>void) => void
interface IDSResourceLifecycleValidateEventHandlers {
beforeValidate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
validate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
afterValidate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
beforeValidate?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
validate?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
afterValidate?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
}
interface IDSResourceLifecycleCreateEventHandlers {
beforeCreate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
afterCreate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
}
interface IDSResourceLifecycleCreateInstanceEventHandlers {
beforeCreateInstance?: (resourceName:string, data:any)=>void;
afterCreateInstance?: (resourceName:string, data:any)=>void;
beforeCreate?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
afterCreate?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
}
interface IDSResourceLifecycleUpdateEventHandlers {
beforeUpdate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
afterUpdate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
beforeUpdate?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
afterUpdate?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
}
interface IDSResourceLifecycleDestroyEventHandlers {
beforeDestroy?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
afterDestroy?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
beforeDestroy?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
afterDestroy?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
}
interface IDSResourceLifecycleCreateInstanceEventHandlers {
beforeCreateInstance?: DSSyncLifecycleHookHandler;
afterCreateInstance?: DSSyncLifecycleHookHandler;
}
interface IDSResourceLifecycleInjectEventHandlers {
beforeInject?: (resourceName:string, data:any)=>void;
afterInject?: (resourceName:string, data:any)=>void;
beforeInject?: DSSyncLifecycleHookHandler;
afterInject?: DSSyncLifecycleHookHandler;
}
interface IDSResourceLifecycleEjectEventHandlers {
beforeEject?: (resourceName:string, data:any)=>void;
afterEject?: (resourceName:string, data:any)=>void;
beforeEject?: DSSyncLifecycleHookHandler;
afterEject?: DSSyncLifecycleHookHandler;
}
interface IDSResourceLifecycleReapEventHandlers {
beforeReap?: (resourceName:string, data:any)=>void;
afterReap?: (resourceName:string, data:any)=>void;
beforeReap?: DSSyncLifecycleHookHandler;
afterReap?: DSSyncLifecycleHookHandler;
}
interface IDSResourceLifecycleFindEventHandlers {
afterFind?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
}
interface IDSResourceLifecycleFindAllEventHandlers {
afterFindAll?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
}
interface IDSResourceLifecycleLoadRelationsEventHandlers {
afterLoadRelations?: DSAsyncLifecycleHookHandler | DSAsyncLifecycleHookHandlerCb;
}
interface IDSResourceLifecycleCreateCollectionEventHandlers {
beforeCreateCollection?: DSSyncLifecycleHookHandler;
afterCreateCollection?: DSSyncLifecycleHookHandler;
}
interface IDSResourceLifecycleEventHandlers extends IDSResourceLifecycleCreateEventHandlers,
@@ -247,8 +277,11 @@ declare module JSData {
IDSResourceLifecycleDestroyEventHandlers,
IDSResourceLifecycleInjectEventHandlers,
IDSResourceLifecycleEjectEventHandlers,
IDSResourceLifecycleReapEventHandlers {
IDSResourceLifecycleReapEventHandlers,
IDSResourceLifecycleFindEventHandlers,
IDSResourceLifecycleFindAllEventHandlers,
IDSResourceLifecycleLoadRelationsEventHandlers,
IDSResourceLifecycleCreateCollectionEventHandlers {
}
// errors
@@ -271,19 +304,31 @@ declare module JSData {
// DSAdapter interface
interface IDSAdapter {
create<T>(config:DSResourceDefinition<T>, attrs:Object, options?:DSConfiguration):JSDataPromise<T>;
create(config:DSResourceDefinition<any>, attrs:Object, options?:DSConfiguration):JSDataPromise<any>;
destroy<T>(config:DSResourceDefinition<T>, id:string | number, options?:DSConfiguration):JSDataPromise<any>;
destroy(config:DSResourceDefinition<any>, id:string | number, options?:DSConfiguration):JSDataPromise<void>;
destroyAll(config:DSResourceDefinition<any>, params:DSFilterArg, options?:DSConfiguration):JSDataPromise<void>;
destroyAll<T>(config:DSResourceDefinition<T>, params:DSFilterParams, options?:DSConfiguration):JSDataPromise<any>;
find(config:DSResourceDefinition<any>, id:string | number, options?:DSConfiguration):JSDataPromise<any>;
findAll(config:DSResourceDefinition<any>, params?:DSFilterArg, options?:DSConfiguration):JSDataPromise<any>;
find<T>(config:DSResourceDefinition<T>, id:string | number, options?:DSConfiguration):JSDataPromise<T>;
update(config:DSResourceDefinition<any>, id:string | number, attrs:Object, options?:DSConfiguration):JSDataPromise<any>;
updateAll(config:DSResourceDefinition<any>, attrs:Object, params?:DSFilterArg, options?:DSConfiguration):JSDataPromise<any>;
}
findAll<T>(config:DSResourceDefinition<T>, params?:DSFilterParams, options?:DSConfiguration):JSDataPromise<T>;
// Custom action config
interface DSActionConfig {
adapter?: string;
endpoint?: string;
pathname?: string;
method?: string;
}
update<T>(config:DSResourceDefinition<T>, id:string | number, attrs:Object, options?:DSConfiguration):JSDataPromise<T>;
updateAll<T>(config:DSResourceDefinition<T>, attrs:Object, params?:DSFilterParams & T, options?:DSConfiguration):JSDataPromise<T[]>;
// Custom action method definition
// options are passed to adapter.HTTP() method-call, js-data-http adapter by default uses AXIOS but can also be $http in case of angular
// or a custom adapter implementation. The adapter can be set via the DSActionConfig.
interface DSActionFn {
<T>(id:string | number, options?:Object):JSDataPromise<T>
}
}
@@ -295,6 +340,5 @@ declare var JSData:{
//Support node require
declare module 'js-data' {
export = JSData;
}
+585
View File
@@ -0,0 +1,585 @@
/// <reference path="js-data-1.5.4.d.ts" />
interface IUser {
id?: number;
name?: string;
age?: number;
first?: string;
last?: string;
comments?:Array<any>;
profile?:any;
}
interface IUserWithMethod {
fullName:()=>string;
}
interface IUserWithComputedProperty extends IUser {
fullName?: string;
}
var store = new JSData.DS();
// simplest model definition
var User = store.defineResource<IUser>('user');
User.find(1).then(function (user:IUser) {
user; // { id: 1, name: 'John' }
});
var user:IUser = User.createInstance({name: 'John'});
var store = new JSData.DS();
var User2 = store.defineResource('user');
var user:IUser = User2.inject({id: 1, name: 'John'});
var user2:IUser = User2.inject({id: 1, age: 30});
user; // User { id: 1, name: 'John', age: 30 }
user2; // User { id: 1, name: 'John', age: 30 }
User.get(1); // User { id: 1, name: 'John', age: 30 }
user === user2; // true
user === User.get(1); // true
user2 === User.get(1); // true
var store = new JSData.DS({
// set a default lifecycle hook
afterCreate: function () {
}
});
var User = store.defineResource<IUser>({
name: 'user',
// override the hook for this resource
afterCreate: function () {
}
});
User.create({
name: 'john'
}, {
// override the hook just for this method call
afterCreate: function () {
}
}).then(()=> {
});
var store = new JSData.DS();
var UserWithMethodResource = store.defineResource<IUserWithMethod>({
name: 'user',
methods: {
fullName: function () {
return this.first + ' ' + this.last;
}
}
});
var userWithMethod = UserWithMethodResource.createInstance({first: 'John', last: 'Anderson'});
userWithMethod.fullName(); // "John Anderson"
var store = new JSData.DS();
var UserWithComputedProperty = store.defineResource<IUserWithComputedProperty>({
name: 'user',
computed: {
// each function's argument list defines the fields
// that the computed property depends on
fullName: ['first', 'last', function (first:string, last:string) {
return first + ' ' + last;
}],
// shortand, use the array syntax above if you want
// you computed properties to work after you've
// minified your code. Shorthand style won't work when minified
initials: function (first:string, last:string) {
return first.toUpperCase()[0] + '. ' + last.toUpperCase()[0] + '.';
}
}
});
var userWithComputedProperty:IUserWithComputedProperty = UserWithComputedProperty.inject({
id: 1,
first: 'John',
last: 'Anderson'
});
userWithComputedProperty.fullName; // "John Anderson"
userWithComputedProperty.first = 'Fred';
// js-data relies on dirty-checking, so the
// computed property (probably) hasn't been updated yet
userWithComputedProperty.fullName; // "John Anderson"
// If your browser supports Object.observe this will have no effect
// otherwise it will trigger the dirty-checking
store.digest();
userWithComputedProperty.fullName; // "Fred Anderson"
interface IComment {
comments?: any;
profile?: any;
}
var aComment:JSData.DSResourceDefinition<IComment> = store.defineResource<IComment>('comment');
// Get all comments where comment.userId == 5
aComment.filter({
where: {
userId: {
'==': 5
}
}
});
// Get all comments where comment.userId == 5
aComment.filter({
userId: 5
});
// Get all comments where comment.userId === 5
aComment.filter({
where: {
userId: {
'===': 5
}
}
});
// Get all comments where comment.userId != 5
aComment.filter({
where: {
userId: {
'!=': 5
}
}
});
// Get all comments where comment.userId !== 5
aComment.filter({
where: {
userId: {
'!==': 5
}
}
});
// Get all users where user.age > 30
User.filter({
where: {
age: {
'>': 30
}
}
});
// Get all users where user.age >= 30
User.filter({
where: {
age: {
'>=': 30
}
}
});
// Get all users where user.age < 30
User.filter({
where: {
age: {
'<': 30
}
}
});
// Get all users where user.name is in "John Anderson"
User.filter({
where: {
name: {
'in': 'John Anderson'
}
}
});
// Get all users where user.role is in ["admin", "owner"]
User.filter({
where: {
role: {
'in': ['admin', 'owner']
}
}
});
// Get all users where user.name is NOT in "John Anderson"
User.filter({
where: {
name: {
'notIn': 'John Anderson'
}
}
});
// Get all users where user.role is NOT in ["admin", "owner"]
User.filter({
where: {
role: {
'notIn': ['admin', 'owner']
}
}
});
// Get all users where user.name contains "John"
User.filter({
where: {
name: {
'contains': 'John'
}
}
});
// Get all users where user.roles contains "admin"
User.filter({
where: {
roles: {
'contains': 'admin'
}
}
});
// Sorts users by age in ascending order
User.filter({
orderBy: 'age'
});
// Sorts users by age in descending order
User.filter({
orderBy: ['age', 'DESC']
});
// Sorts users by age in descending order and then sort by name in ascending order to break a tie
User.filter({
orderBy: [
['age', 'DESC'],
['name', 'ASC']
]
});
var PAGE_SIZE = 20;
var currentPage = 1;
interface IPost {
}
var Post:JSData.DSResourceDefinition<IPost>;
// Grab the first "page" of posts
Post.filter({
offset: PAGE_SIZE * (currentPage - 1),
limit: PAGE_SIZE
});
var User3 = store.defineResource({
name: 'user',
relations: {
hasMany: {
comment: {
localField: 'comments',
foreignKey: 'userId'
}
},
hasOne: {
profile: {
localField: 'profile',
foreignKey: 'userId'
}
},
belongsTo: {
organization: {
localKey: 'organizationId',
localField: 'organization',
// if you add this to a belongsTo relation
// then js-data will attempt to use
// a nested url structure, e.g. /organization/15/user/4
parent: true
}
}
}
});
var Organization = store.defineResource({
name: 'organization',
relations: {
hasMany: {
// this is an example of multiple relations
// of the same type to the same resource
user: [
{
localField: 'users',
foreignKey: 'organizationId'
},
{
localField: 'owners',
foreignKey: 'organizationId'
}
]
}
}
});
var Profile = store.defineResource({
name: 'profile',
relations: {
belongsTo: {
user: {
localField: 'user',
localKey: 'userId'
}
}
}
});
var OtherComment = store.defineResource<IComment>({
name: 'comment',
relations: {
belongsTo: {
user: {
localField: 'user',
localKey: 'userId'
}
}
}
});
User.find(10).then(function (user:IUser) {
// let's assume the server only returned the user
user.comments; // undefined
user.profile; // undefined
User.loadRelations(user, ['comment', 'profile']).then(function (user:IUser) {
user.comments; // array
user.profile; // object
});
});
var OtherOtherComment = store.defineResource<IComment>({
name: 'comment',
relations: {
belongsTo: {
post: {
parent: true,
localKey: 'postId',
localField: 'post'
}
}
}
});
// The comment isn't in the data store yet, so js-data wouldn't know
// what the id of the parent "post" would be, so we pass it in manually
OtherOtherComment.find(5, {params: {postId: 4}}); // GET /post/4/comment/5
// vs
var promise = OtherOtherComment.find(5); // GET /comment/5
promise.then().catch().finally();
OtherOtherComment.inject(<IComment>{id: 1, postId: 2});
// We don't have to provide the parentKey here
// because js-data found it in the comment
OtherOtherComment.update(1, {content: 'stuff'}); // PUT /post/2/comment/1
// If you don't want the nested for just one of the calls then
// you can do the following:
OtherOtherComment.update(1, {content: 'stuff'}, {params: {postId: false}}); // PUT /comment/1
var store = new JSData.DS({
// set the default
beforeCreate: function (resource, data, cb) {
// do something general
cb(null, data);
}
});
var User4 = store.defineResource({
name: 'user',
// set just for this resource
beforeCreate: function (resource, data, cb) {
// do something more specific to "users"
cb(null, data);
}
});
User4.create({name: 'John'}, {
// set just for this method call
beforeCreate: function (resource, data, cb) {
// do something specific for this method call
cb(null, data);
}
});
module CustomAdapterTest {
class MyCustomAdapter implements JSData.IDSAdapter {
// All of the methods shown here must return a promise
// "definition" is a resource defintion that would
// be returned by DS#defineResource
// "options" would be the options argument that
// was passed into the DS method that is calling
// the adapter method
create(definition:JSData.DSResourceDefinition<any>, attrs:Object, options:JSData.DSConfiguration):JSData.JSDataPromise<any> {
// Must resolve the promise with the created item
var promise:JSData.JSDataPromise<any>;
return promise;
}
find(definition:JSData.DSResourceDefinition<any>, id:any, options:JSData.DSConfiguration):JSData.JSDataPromise<any> {
// Must resolve the promise with the found item
var promise:JSData.JSDataPromise<any>;
return promise;
}
findAll(definition:JSData.DSResourceDefinition<any>, params:JSData.DSFilterParams, options:JSData.DSConfiguration):JSData.JSDataPromise<any> {
// Must resolve the promise with the found items
var promise:JSData.JSDataPromise<any>;
return promise;
}
update(definition:JSData.DSResourceDefinition<any>, id:any, attrs:Object, options:JSData.DSConfiguration):JSData.JSDataPromise<any> {
// Must resolve the promise with the updated items
var promise:JSData.JSDataPromise<any>;
return promise;
}
updateAll(definition:JSData.DSResourceDefinition<any>, attrs:Object, params:JSData.DSFilterParams, options:JSData.DSConfiguration):JSData.JSDataPromise<any> {
// Must resolve the promise with the updated items
var promise:JSData.JSDataPromise<any>;
return promise;
}
destroy(definition:JSData.DSResourceDefinition<any>, id:any, options:JSData.DSConfiguration):JSData.JSDataPromise<any> {
// Must return a promise
var promise:JSData.JSDataPromise<any>;
return promise;
}
destroyAll(definition:JSData.DSResourceDefinition<any>, params:JSData.DSFilterParams, options:JSData.DSConfiguration):JSData.JSDataPromise<any> {
// Must return a promise
var promise:JSData.JSDataPromise<any>;
return promise;
}
}
var store = new JSData.DS();
store.registerAdapter('mca', new MyCustomAdapter(), {default: true});
// the data store will now use your custom adapter by default
}
/**
* showing the use of open ended interface to realize typings
* on the Datastore.definitions object where all resource definitions
* are saved.
*/
interface MyCustomDataStore {
myResource: JSData.DSResourceDefinition<MyResourceDefinition>
}
interface MyResourceDefinition {
}
module JSData {
interface DS {
definitions: MyCustomDataStore;
}
}
var store = new JSData.DS();
var myResourceDefinition = store.defineResource<MyResourceDefinition>('myResource');
myResourceDefinition = store.definitions.myResource;
/**
* Custom action on datastore resource
*/
interface Resource {
someProp:string;
}
interface ActionsForResource {
myAction:JSData.DSActionFn;
myOtherAction:JSData.DSActionFn;
}
var myOtherAction:JSData.DSActionConfig = {
method: 'GET',
endpoint: 'goHere'
};
var resourceWithCustomActions = store.defineResource<Resource, ActionsForResource>({
name: 'actionResource',
actions: {
myAction: {
method: 'POST'
},
myOtherAction: myOtherAction
}
});
resourceWithCustomActions.myAction<number>(3).then((result)=>{
var theCustomResult:number = result;
});
resourceWithCustomActions.myOtherAction<void>(2, {data:'blub'}).then(()=>{
// success
});
resourceWithCustomActions.find(1).then((result)=>{
var aProperty = result.someProp;
});
/**
* Instance shorthands
*/
var customActionResourceInstance = resourceWithCustomActions.get(1);
customActionResourceInstance.DSCompute();
customActionResourceInstance.DSChanges();
customActionResourceInstance.DSChangeHistory();
customActionResourceInstance.DSHasChanges();
customActionResourceInstance.DSLastModified();
customActionResourceInstance.DSLastSaved();
customActionResourceInstance.DSPrevious();
customActionResourceInstance.DSCreate();
customActionResourceInstance.DSDestroy();
customActionResourceInstance.DSLink();
customActionResourceInstance.DSLinkInverse();
customActionResourceInstance.DSLoadRelations('myRelation');
customActionResourceInstance.DSRefresh();
customActionResourceInstance.DSSave();
customActionResourceInstance.DSUnlinkInverse();
customActionResourceInstance.DSUpdate();
+317
View File
@@ -0,0 +1,317 @@
// Type definitions for JSData v1.5.4
// Project: https://github.com/js-data/js-data
// Definitions by: Stefan Steinhart <https://github.com/reppners>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///////////////////////////////////////////////////////////////////////////////
// js-data module (js-data.js)
///////////////////////////////////////////////////////////////////////////////
// defining what exists in JSData and how it looks
declare module JSData {
interface JSDataPromise<R> {
then<U>(onFulfilled?: (value: R) => U | JSDataPromise<U>, onRejected?: (error: any) => U | JSDataPromise<U>): JSDataPromise<U>;
catch<U>(onRejected?: (error: any) => U | JSDataPromise<U>): JSDataPromise<U>;
// enhanced with finally
finally<U>(finallyCb?:() => U):JSDataPromise<U>;
}
interface DS {
new(config?:DSConfiguration):DS;
// rather undocumented
errors:DSErrors;
// those are objects containing the defined resources and adapters
definitions:any;
adapters:any;
defaults:DSConfiguration;
// async
create<T>(resourceName:string, attrs:Object, options?:DSConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
destroy(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<any>;
destroyAll(resourceName:string, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<any>;
find<T>(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
findAll<T>(resourceName:string, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
loadRelations<T>(resourceName:string, idOrInstance:string | number | Object, relations:string | Array<string>, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
update<T>(resourceName:string, id:string | number, attrs:Object, options?:DSSaveConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
updateAll<T>(resourceName:string, attrs:Object, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
reap(resourceName:string, options?:DSConfiguration):JSDataPromise<any>;
refresh<T>(resourceName:string, id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
save<T>(resourceName:string, id:string | number, options?:DSSaveConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
// sync
changeHistory(resourceName:string, id?:string | number):Array<Object>;
changes(resourceName:string, id:string | number):Object;
compute(resourceName:string, idOrInstance:number | string | Object ):void;
createInstance<T>(resourceName:string, attrs?:T, options?:DSAdapterOperationConfiguration):T & DSInstanceShorthands<T>;
digest():void;
eject<T>(resourceName:string, id:string | number, options?:DSConfiguration):T & DSInstanceShorthands<T>;
ejectAll<T>(resourceName:string, params:DSFilterArg, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
filter<T>(resourceName:string, params:DSFilterArg, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
get<T>(resourceName:string, id:string | number, options?:DSConfiguration):T & DSInstanceShorthands<T>;
getAll<T>(resourceName:string, ids?:Array<string | number>):Array<T & DSInstanceShorthands<T>>;
hasChanges(resourceName:string, id:string | number):boolean;
inject<T>(resourceName:string, item:T, options?:DSConfiguration):T & DSInstanceShorthands<T>;
inject<T>(resourceName:string, items:Array<T>, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
is(resourceName:string, object:Object): boolean;
lastModified(resourceName:string, id?:string | number):number; // timestamp
lastSaved(resourceName:string, id?:string | number):number; // timestamp
link<T>(resourceName:string, id:string | number, relations?:Array<string>):T & DSInstanceShorthands<T>;
linkAll<T>(resourceName:string, params:DSFilterArg, relations?:Array<string>):T & DSInstanceShorthands<T>;
linkInverse<T>(resourceName:string, id:string | number, relations?:Array<string>):T & DSInstanceShorthands<T>;
previous<T>(resourceName:string, id:string | number):T & DSInstanceShorthands<T>;
revert<T>(resourceName:string, id:string | number):T & DSInstanceShorthands<T>;
unlinkInverse<T>(resourceName:string, id:string | number, relations?:Array<string>):T & DSInstanceShorthands<T>;
defineResource<T>(resourceNameOrDefinition:string | DSResourceDefinitionConfiguration):DSResourceDefinition<T>;
defineResource<T, TActions>(resourceNameOrDefinition:string | DSResourceDefinitionConfiguration):DSResourceDefinition<T> & TActions;
registerAdapter(adapterId:string, adapter:IDSAdapter, options?:{default: boolean}):void;
}
interface DSConfiguration extends IDSResourceLifecycleEventHandlers {
actions?: Object;
allowSimpleWhere?: boolean;
basePath?: string;
bypassCache?: boolean;
cacheResponse?: boolean;
defaultAdapter?: string;
defaultFilter?: (collection:Array<any>, resourceName:string, params:DSFilterArg, options:DSConfiguration)=>Array<any>;
eagerEject?: boolean;
endpoint?: string;
error?: boolean | ((message?:any, ...optionalParams:any[])=> void);
fallbackAdapters?: Array<string>;
findAllFallbackAdapters?: Array<string>;
findAllStrategy?: string;
findBelongsTo?: boolean;
findFallbackAdapters?: Array<string>;
findHasOne?: boolean;
findHasMany?: boolean;
findInverseLinks?: boolean;
findStrategy?: string
idAttribute?: string;
ignoredChanges?: Array<RegExp | string>;
keepChangeHistory?: boolean;
loadFromServer?: boolean;
log?: boolean | ((message?: any, ...optionalParams: any[])=> void);
maxAge?: number;
notify?: boolean;
reapAction?: string;
reapInterval?: number;
resetHistoryOnInject?: boolean;
strategy?: string;
upsert?: boolean;
useClass?: boolean;
useFilter?: boolean;
}
interface DSAdapterOperationConfiguration extends DSConfiguration {
adapter?: string;
params?: {
[paramName: string]: string | number | boolean;
};
}
interface DSSaveConfiguration extends DSAdapterOperationConfiguration {
changesOnly?: boolean;
}
interface DSResourceDefinitionConfiguration extends DSConfiguration {
name: string;
computed?: any;
methods?: any;
relations?: {
hasMany?: Object;
hasOne?: Object;
belongsTo?: Object;
};
}
interface DSResourceDefinition<T> extends DSResourceDefinitionConfiguration {
//async
create<TInject>(attrs:TInject, options?:DSConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
destroy(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<void>;
destroyAll(params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<void>;
find(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
findAll(params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
loadRelations(idOrInstance:string | number | Object, relations:string | Array<string>, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
update(id:string | number, attrs:Object, options?:DSSaveConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
updateAll(attrs:Object, params?:DSFilterArg, options?:DSAdapterOperationConfiguration):JSDataPromise<Array<T & DSInstanceShorthands<T>>>;
reap(options?:DSConfiguration):JSDataPromise<void>;
refresh(id:string | number, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
save(id:string | number, options?:DSSaveConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
// sync
changeHistory(id?:string | number):Array<Object>;
changes(id:string | number):Object;
compute(idOrInstance:number | string | Object ):void;
createInstance<TInject>(attrs?:TInject, options?:DSAdapterOperationConfiguration):T & DSInstanceShorthands<T>;
digest():void;
eject(id:string | number, options?:DSConfiguration):T & DSInstanceShorthands<T>;
ejectAll(params:DSFilterArg, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
filter(params:DSFilterArg, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
get(id:string | number, options?:DSConfiguration):T & DSInstanceShorthands<T>;
getAll(ids?:Array<string | number>):Array<T & DSInstanceShorthands<T>>;
hasChanges(id:string | number):boolean;
inject(item:T, options?:DSConfiguration):T & DSInstanceShorthands<T>;
inject(items:Array<T>, options?:DSConfiguration):Array<T & DSInstanceShorthands<T>>;
is(object:Object): boolean;
lastModified(id?:string | number):number; // timestamp
lastSaved(id?:string | number):number; // timestamp
link(id:string | number, relations?:Array<string>):T & DSInstanceShorthands<T>;
linkAll(params:DSFilterArg, relations?:Array<string>):T & DSInstanceShorthands<T>;
linkInverse(id:string | number, relations?:Array<string>):T & DSInstanceShorthands<T>;
previous(id:string | number):T & DSInstanceShorthands<T>;
unlinkInverse(id:string | number, relations?:Array<string>):T & DSInstanceShorthands<T>;
}
export interface DSInstanceShorthands<T> {
DSCompute():void;
DSRefresh(options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSSave(options?:DSSaveConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSUpdate(options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSDestroy(options?:DSAdapterOperationConfiguration):JSDataPromise<void>;
DSCreate(options?:DSConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSLoadRelations(relations:string | Array<string>, options?:DSAdapterOperationConfiguration):JSDataPromise<T & DSInstanceShorthands<T>>;
DSChangeHistory():Array<Object>;
DSChanges():Object;
DSHasChanges():boolean;
DSLastModified():number; // timestamp
DSLastSaved():number; // timestamp
DSLink(relations?:Array<string>):T & DSInstanceShorthands<T>;
DSLinkInverse(relations?:Array<string>):T & DSInstanceShorthands<T>;
DSPrevious():T & DSInstanceShorthands<T>;
DSUnlinkInverse(relations?:Array<string>):T & DSInstanceShorthands<T>;
}
interface DSFilterParams {
where?: Object;
limit?: number;
skip?: number;
offset?: number;
orderBy?: string | Array<string> | Array<Array<string>>;
sort?: string | Array<string> | Array<Array<string>>;
}
type DSFilterArg = DSFilterParams | Object;
interface IDSResourceLifecycleValidateEventHandlers {
beforeValidate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
validate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
afterValidate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
}
interface IDSResourceLifecycleCreateEventHandlers {
beforeCreate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
afterCreate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
}
interface IDSResourceLifecycleCreateInstanceEventHandlers {
beforeCreateInstance?: (resourceName:string, data:any)=>void;
afterCreateInstance?: (resourceName:string, data:any)=>void;
}
interface IDSResourceLifecycleUpdateEventHandlers {
beforeUpdate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
afterUpdate?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
}
interface IDSResourceLifecycleDestroyEventHandlers {
beforeDestroy?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
afterDestroy?: (resourceName:string, data:any, cb:(err:any, data?:any)=>void)=>void;
}
interface IDSResourceLifecycleInjectEventHandlers {
beforeInject?: (resourceName:string, data:any)=>void;
afterInject?: (resourceName:string, data:any)=>void;
}
interface IDSResourceLifecycleEjectEventHandlers {
beforeEject?: (resourceName:string, data:any)=>void;
afterEject?: (resourceName:string, data:any)=>void;
}
interface IDSResourceLifecycleReapEventHandlers {
beforeReap?: (resourceName:string, data:any)=>void;
afterReap?: (resourceName:string, data:any)=>void;
}
interface IDSResourceLifecycleEventHandlers extends IDSResourceLifecycleCreateEventHandlers,
IDSResourceLifecycleCreateInstanceEventHandlers,
IDSResourceLifecycleValidateEventHandlers,
IDSResourceLifecycleUpdateEventHandlers,
IDSResourceLifecycleDestroyEventHandlers,
IDSResourceLifecycleInjectEventHandlers,
IDSResourceLifecycleEjectEventHandlers,
IDSResourceLifecycleReapEventHandlers {
}
// errors
interface DSErrors {
// types
IllegalArgumentError:DSError;
IA:DSError;
RuntimeError:DSError;
R:DSError;
NonexistentResourceError:DSError;
NER:DSError;
}
interface DSError extends Error {
new (message?:string):DSError;
message: string;
type: string;
}
// DSAdapter interface
interface IDSAdapter {
create<T>(config:DSResourceDefinition<T>, attrs:Object, options?:DSConfiguration):JSDataPromise<T>;
destroy<T>(config:DSResourceDefinition<T>, id:string | number, options?:DSConfiguration):JSDataPromise<any>;
destroyAll<T>(config:DSResourceDefinition<T>, params:DSFilterArg, options?:DSConfiguration):JSDataPromise<any>;
find<T>(config:DSResourceDefinition<T>, id:string | number, options?:DSConfiguration):JSDataPromise<T>;
findAll<T>(config:DSResourceDefinition<T>, params?:DSFilterArg, options?:DSConfiguration):JSDataPromise<T>;
update<T>(config:DSResourceDefinition<T>, id:string | number, attrs:Object, options?:DSConfiguration):JSDataPromise<T>;
updateAll<T>(config:DSResourceDefinition<T>, attrs:Object, params?:DSFilterArg, options?:DSConfiguration):JSDataPromise<T>;
}
// Custom action config
interface DSActionConfig {
adapter?: string;
endpoint?: string;
pathname?: string;
method?: string;
}
// Custom action method definition
// options are passed to adapter.HTTP() method-call, js-data-http adapter by default uses AXIOS but can also be $http in case of angular
// or a custom adapter implementation. The adapter can be set via the DSActionConfig.
interface DSActionFn {
<T>(id:string | number, options?:Object):JSDataPromise<T>
}
}
// declaring the existing global js object
declare var JSData:{
DS: JSData.DS;
DSErrors: JSData.DSErrors;
};
//Support node require
declare module 'js-data' {
export = JSData;
}
@@ -0,0 +1,11 @@
/// <reference path="js-data-1.5.4.d.ts" />
import JSData = require('js-data');
var store = new JSData.DS();
// simplest model definition
var User = store.defineResource('user');
User.find(1).then(function (user: any) {
user; // { id: 1, name: 'John' }
});