Merge pull request #30365 from agoldis/parse-2.1.0

[@types/parse] Major version bump to 2.0.0 due to Parse 2.1.0
This commit is contained in:
Armando Aguirre
2018-11-19 11:32:17 -08:00
committed by GitHub
8 changed files with 1975 additions and 392 deletions
+1 -2
View File
@@ -4,8 +4,6 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="parse" />
declare namespace ParseMockDB {
function mockDB(): void;
function unMockDB(): void;
@@ -18,5 +16,6 @@ declare namespace ParseMockDB {
}
declare module "parse-mockdb" {
import * as Parse from 'parse'
export = ParseMockDB;
}
+4
View File
@@ -13,6 +13,10 @@
"typeRoots": [
"../"
],
"paths": {
"parse": ["parse/v1"],
"parse/*": ["parse/v1/*"]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
+87 -294
View File
@@ -1,4 +1,4 @@
// Type definitions for parse 1.11.1
// Type definitions for parse 2.1.0
// Project: https://parseplatform.org/
// Definitions by: Ullisen Media Group <http://ullisenmedia.com>
// David Poetzsch-Heffter <https://github.com/dpoetzsch>
@@ -6,12 +6,11 @@
// Flavio Negrão <https://github.com/flavionegrao>
// Wes Grimes <https://github.com/wesleygrimes>
// Otherwise SAS <https://github.com/owsas>
// Andrew Goldis <https://github.com/agoldis>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="node" />
/// <reference types="jquery" />
/// <reference types="underscore" />
declare namespace Parse {
@@ -67,53 +66,6 @@ declare namespace Parse {
silent?: boolean;
}
/**
* A Promise is returned by async methods as a hook to provide callbacks to be
* called when the async task is fulfilled.
*
* <p>Typical usage would be like:<pre>
* query.find().then(function(results) {
* results[0].set("foo", "bar");
* return results[0].saveAsync();
* }).then(function(result) {
* console.log("Updated " + result.id);
* });
* </pre></p>
*
* @see Parse.Promise.prototype.then
* @class
*/
interface IPromise<T> {
then<U>(resolvedCallback: (...values: T[]) => IPromise<U>, rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise<U>;
catch<U>(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise<U>;
}
class Promise<T> implements IPromise<T> {
static as<U>(resolvedValue: U): Promise<U>;
static error(error: any): Promise<any>;
static is(possiblePromise: any): Boolean;
static when(promises: IPromise<any>[]): Promise<any>;
static when(...promises: IPromise<any>[]): Promise<any>;
always(callback: Function): Promise<T>;
done(callback: Function): Promise<T>;
fail(callback: Function): Promise<T>;
reject(error: any): void;
resolve(result: any): void;
then<U>(resolvedCallback: (...values: T[]) => IPromise<U>,
rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (...values: T[]) => U,
rejectedCallback?: (reason: any) => IPromise<U>): IPromise<U>;
then<U>(resolvedCallback: (...values: T[]) => U,
rejectedCallback?: (reason: any) => U): IPromise<U>;
catch<U>(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise<U>;
}
interface Pointer {
__type: string;
className: string;
@@ -251,38 +203,6 @@ declare namespace Parse {
milesTo(point: GeoPoint): number;
}
/**
* History serves as a global router (per frame) to handle hashchange
* events or pushState, match the appropriate route, and trigger
* callbacks. You shouldn't ever have to create one of these yourself
* — you should use the reference to <code>Parse.history</code>
* that will be created for you automatically if you make use of
* Routers with routes.
* @class
*
* <p>A fork of Backbone.History, provided for your convenience. If you
* use this class, you must also include jQuery, or another library
* that provides a jQuery-compatible $ function. For more information,
* see the <a href="http://documentcloud.github.com/backbone/#History">
* Backbone documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
class History {
handlers: any[];
interval: number;
fragment: string;
checkUrl(e?: any): void;
getFragment(fragment?: string, forcePushState?: boolean): string;
getHash(windowOverride: Window): string;
loadUrl(fragmentOverride: any): boolean;
navigate(fragment: string, options?: any): any;
route(route: any, callback: Function): void;
start(options: any): boolean;
stop(): void;
}
/**
* A class that is used to access all of the children of a many-to-many relationship.
* Each instance of Parse.Relation is associated with a particular parent object and key.
@@ -323,14 +243,12 @@ declare namespace Parse {
* </pre></p>
*
* @param {Object} attributes The initial set of data to store in the object.
* @param {Object} options A set of Backbone-like options for creating the
* object. The only option currently supported is "collection".
* @param {Object} options The options for this object instance.
* @see Parse.Object.extend
*
* @class
*
* <p>The fundamental unit of Parse data, which implements the Backbone Model
* interface.</p>
* Creates a new model with defined attributes.
*/
class Object extends BaseObject {
@@ -430,120 +348,6 @@ declare namespace Parse {
appIdentifier: string;
}
/**
* Creates a new instance with the given models and options. Typically, you
* will not call this method directly, but will instead make a subclass using
* <code>Parse.Collection.extend</code>.
*
* @param {Array} models An array of instances of <code>Parse.Object</code>.
*
* @param {Object} options An optional object with Backbone-style options.
* Valid options are:<ul>
* <li>model: The Parse.Object subclass that this collection contains.
* <li>query: An instance of Parse.Query to use when fetching items.
* <li>comparator: A string property name or function to sort by.
* </ul>
*
* @see Parse.Collection.extend
*
* @class
*
* <p>Provides a standard collection class for our sets of models, ordered
* or unordered. For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Collection">Backbone
* documentation</a>.</p>
*/
class Collection<T> extends Events implements IBaseObject {
model: Object;
models: Object[];
query: Query<Object>;
comparator: (object: Object) => any;
constructor(models?: Object[], options?: Collection.Options);
static extend(instanceProps: any, classProps: any): any;
initialize(): void;
add(models: any[], options?: Collection.AddOptions): Collection<T>;
at(index: number): Object;
chain(): _._Chain<Collection<T>>;
fetch(options?: Collection.FetchOptions): Promise<T>;
create(model: Object, options?: Collection.CreateOptions): Object;
get(id: string): Object;
getByCid(cid: any): any;
pluck(attr: string): any[];
remove(model: any, options?: Collection.RemoveOptions): Collection<T>;
remove(models: any[], options?: Collection.RemoveOptions): Collection<T>;
reset(models: any[], options?: Collection.ResetOptions): Collection<T>;
sort(options?: Collection.SortOptions): Collection<T>;
toJSON(): any;
}
namespace Collection {
interface Options {
model?: Object;
query?: Query<Object>;
comparator?: string;
}
interface AddOptions extends SilentOption {
/**
* The index at which to add the models.
*/
at?: number;
}
interface CreateOptions extends SuccessFailureOptions, WaitOption, SilentOption, ScopeOptions {
}
interface FetchOptions extends SuccessFailureOptions, SilentOption, ScopeOptions { }
interface RemoveOptions extends SilentOption { }
interface ResetOptions extends SilentOption { }
interface SortOptions extends SilentOption { }
}
/**
* @class
*
* <p>Parse.Events is a fork of Backbone's Events module, provided for your
* convenience.</p>
*
* <p>A module that can be mixed in to any object in order to provide
* it with custom events. You may bind callback functions to an event
* with `on`, or remove these functions with `off`.
* Triggering an event fires all callbacks in the order that `on` was
* called.
*
* <pre>
* var object = {};
* _.extend(object, Parse.Events);
* object.on('expand', function(){ alert('expanded'); });
* object.trigger('expand');</pre></p>
*
* <p>For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Events">Backbone
* documentation</a>.</p>
*/
class Events {
static off(events: string[], callback?: Function, context?: any): Events;
static on(events: string[], callback?: Function, context?: any): Events;
static trigger(events: string[]): Events;
static bind(): Events;
static unbind(): Events;
on(eventName: string, callback?: Function, context?: any): Events;
off(eventName?: string | null, callback?: Function | null, context?: any): Events;
trigger(eventName: string, ...args: any[]): Events;
bind(eventName: string, callback: Function, context?: any): Events;
unbind(eventName?: string, callback?: Function, context?: any): Events;
}
/**
* Creates a new parse Parse.Query for the given Parse.Object subclass.
* @param objectClass -
@@ -617,7 +421,6 @@ declare namespace Parse {
addDescending(key: string[]): Query<T>;
ascending(key: string): Query<T>;
ascending(key: string[]): Query<T>;
collection(items?: Object[], options?: Collection.Options): Collection<Object>;
containedIn(key: string, values: any[]): Query<T>;
contains(key: string, substring: string): Query<T>;
containsAll(key: string, values: any[]): Query<T>;
@@ -652,7 +455,7 @@ declare namespace Parse {
select(...keys: string[]): Query<T>;
skip(n: number): Query<T>;
startsWith(key: string, prefix: string): Query<T>;
subscribe(): Events;
subscribe(): LiveQuerySubscription;
withinGeoBox(key: string, southwest: GeoPoint, northeast: GeoPoint): Query<T>;
withinKilometers(key: string, point: GeoPoint, maxDistance: number): Query<T>;
withinMiles(key: string, point: GeoPoint, maxDistance: number): Query<T>;
@@ -685,6 +488,88 @@ declare namespace Parse {
}
}
/**
* Represents a LiveQuery Subscription.
*
* @see https://docs.parseplatform.org/js/guide/#live-queries
* @see NodeJS.EventEmitter
*
* Events list
* ---
* `open` - when you call `query.subscribe()`, we send a subscribe request to
* the LiveQuery server, when we get the confirmation from the LiveQuery server,
* this event will be emitted. When the client loses WebSocket connection to the
* LiveQuery server, we will try to auto reconnect the LiveQuery server. If we
* reconnect the LiveQuery server and successfully resubscribe the ParseQuery,
* you'll also get this event.
*
```
subscription.on('open', () => {});
```
* ---
* `create` - when a new ParseObject is created and it fulfills the ParseQuery you subscribe,
* you'll get this event. The object is the ParseObject which is created.
*
```
subscription.on('create', (object: Parse.Object) => {});
```
* ---
* `update` event - when an existing ParseObject which fulfills the ParseQuery you subscribe
* is updated (The ParseObject fulfills the ParseQuery before and after changes),
* you'll get this event. The object is the ParseObject which is updated.
* Its content is the latest value of the ParseObject.
*
```
subscription.on('update', (object: Parse.Object) => {});
```
* ---
* `enter` event - when an existing ParseObject's old value doesn't fulfill the ParseQuery
* but its new value fulfills the ParseQuery, you'll get this event. The object is the
* ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject.
*
```
subscription.on('enter', (object: Parse.Object) => {});
```
* ---
* `update` event - when an existing ParseObject's old value fulfills the ParseQuery but its new value
* doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject
* which leaves the ParseQuery. Its content is the latest value of the ParseObject.
*
```
subscription.on('leave', (object: Parse.Object) => {});
```
* ---
* `delete` event - when an existing ParseObject which fulfills the ParseQuery is deleted, you'll
* get this event. The object is the ParseObject which is deleted.
*
```
subscription.on('delete', (object: Parse.Object) => {});
```
* ---
* `close` event - when the client loses the WebSocket connection to the LiveQuery
* server and we stop receiving events, you'll get this event.
*
```
subscription.on('close', () => {});
```
*/
class LiveQuerySubscription extends NodeJS.EventEmitter {
/**
* Creates an instance of LiveQuerySubscription.
*
* @param {string} id
* @param {string} query
* @param {string} [sessionToken]
*/
constructor(id: string, query: string, sessionToken?: string);
/**
* Closes the subscription.
*
*/
unsubscribe(): void;
}
/**
* Represents a Role on the Parse server. Roles represent groupings of
* Users for the purposes of granting permissions (e.g. specifying an ACL
@@ -723,44 +608,6 @@ declare namespace Parse {
isCurrentSessionRevocable(): boolean;
}
/**
* Routers map faux-URLs to actions, and fire events when routes are
* matched. Creating a new one sets its `routes` hash, if not set statically.
* @class
*
* <p>A fork of Backbone.Router, provided for your convenience.
* For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Router">Backbone
* documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
class Router extends Events {
routes: Router.RouteMap;
constructor(options?: Router.Options);
static extend(instanceProps: any, classProps: any): any;
initialize(): void;
navigate(fragment: string, options?: Router.NavigateOptions): Router;
navigate(fragment: string, trigger?: boolean): Router;
route(route: string, name: string, callback: Function): Router;
}
namespace Router {
interface Options {
routes: RouteMap;
}
interface RouteMap {
[url: string]: string;
}
interface NavigateOptions {
trigger?: boolean;
}
}
/**
* @class
*
@@ -796,60 +643,6 @@ declare namespace Parse {
getSessionToken(): string;
}
/**
* Creating a Parse.View creates its initial element outside of the DOM,
* if an existing element is not provided...
* @class
*
* <p>A fork of Backbone.View, provided for your convenience. If you use this
* class, you must also include jQuery, or another library that provides a
* jQuery-compatible $ function. For more information, see the
* <a href="http://documentcloud.github.com/backbone/#View">Backbone
* documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
class View<T> extends Events {
model: any;
collection: any;
id: string;
cid: string;
className: string;
tagName: string;
el: any;
$el: JQuery;
attributes: any;
constructor(options?: View.Options);
static extend(properties: any, classProperties?: any): any;
$(selector?: string): JQuery;
setElement(element: HTMLElement, delegate?: boolean): View<T>;
setElement(element: JQuery, delegate?: boolean): View<T>;
render(): View<T>;
remove(): View<T>;
make(tagName: any, attributes?: View.Attribute[], content?: any): any;
delegateEvents(events?: any): any;
undelegateEvents(): any;
}
namespace View {
interface Options {
model?: any;
collection?: any;
el?: any;
id?: string;
className?: string;
tagName?: string;
attributes?: Attribute[];
}
interface Attribute {
[attributeName: string]: string | number | boolean;
}
}
namespace Analytics {
+21 -96
View File
@@ -1,22 +1,3 @@
function test_events() {
const object = new Parse.Events();
object.on("alert", (eventName: string) => alert("Triggered " + eventName));
object.trigger("alert", "an event");
const onChange = () => console.log('whatever');
let context: any;
object.off("change", onChange);
object.off("change");
object.off(null, onChange);
object.off(null, null, context);
object.off();
}
class GameScore extends Parse.Object {
constructor(options?: any) {
@@ -145,17 +126,30 @@ function test_query() {
// Find objects with distinct key
query.distinct('name');
const testQuery = Parse.Query.or(query, query);
const testQuery = Parse.Query.or(query, query);
}
class TestCollection extends Parse.Collection<Object> {
async function test_query_promise() {
// Test promise with a query
const findQuery = new Parse.Query('Test');
findQuery.find()
.then(() => {
// success
}).catch(() => {
// error
});
constructor(models?: Parse.Object[]) {
super(models);
const getQuery = new Parse.Query('Test');
try {
await getQuery.get('objectId');
}
catch (error) {
// noop
}
}
function return_a_generic_query(): Parse.Query<Game> {
return new Parse.Query(Game);
}
@@ -164,49 +158,6 @@ function return_a_query(): Parse.Query {
return new Parse.Query(Game);
}
function test_collections() {
let collection = new TestCollection();
const query = new Parse.Query(Game);
query.equalTo("temperature", "hot");
query.greaterThan("degreesF", 100);
collection = query.collection();
collection.comparator = (object) => {
return object.get("temperature");
};
collection.add([
{ "name": "Duke" },
{ "name": "Scarlett" }
]);
collection.fetch().then(
(data) => {
},
(error) => {
console.log("Error: " + error.code + " " + error.message);
}
);
const model = collection.at(0);
// Or you can get it by Parse objectId.
const modelAgain = collection.get(model.id);
// Remove "Duke" from the collection.
collection.remove(model);
// Completely replace all items in the collection.
collection.reset([
{ "name": "Hawk" },
{ "name": "Jane" }
]);
}
function test_file() {
const base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
@@ -500,34 +451,6 @@ function test_push() {
});
}
function test_view() {
const model = Parse.User.current();
const view = new Parse.View<Parse.User>();
}
function test_promise() {
let resolved = Parse.Promise.as(true);
let rejected = Parse.Promise.error("an error object");
Parse.Promise.when([resolved, rejected]).then(function () {
// success
}, function () {
// failed
});
// Test promise with a query
const query = new Parse.Query('Test');
query.find()
.then(() => {
// success
}).catch(() => {
// error
});
// can check whether an object is a Parse.Promise object or not
Parse.Promise.is(resolved);
}
function test_batch_operations() {
const game1 = new Game()
const game2 = new Game()
@@ -557,5 +480,7 @@ function test_query_subscribe() {
subscription.on('create', (game: any) => {
console.log(game);
});
}
// unsubscribe
subscription.unsubscribe();
}
+1200
View File
File diff suppressed because it is too large Load Diff
+561
View File
@@ -0,0 +1,561 @@
function test_events() {
const object = new Parse.Events();
object.on("alert", (eventName: string) => alert("Triggered " + eventName));
object.trigger("alert", "an event");
const onChange = () => console.log('whatever');
let context: any;
object.off("change", onChange);
object.off("change");
object.off(null, onChange);
object.off(null, null, context);
object.off();
}
class GameScore extends Parse.Object {
constructor(options?: any) {
super("GameScore", options);
}
}
class Game extends Parse.Object {
constructor(options?: any) {
super("Game", options);
}
}
function test_object() {
const game = new Game();
if (!game.isNew()) {
console.error("Game should be new");
}
if (game.toPointer().className !== "Game") {
console.log("Class name should be 'Game")
}
game.fetch({
success(g: Game) { }
});
// Create a new instance of that class.
const gameScore = new GameScore();
gameScore.set("score", 1337);
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
// Setting attrs using object
gameScore.set({
level: '10',
difficult: 15
});
const score = gameScore.get("score");
const playerName = gameScore.get("playerName");
const cheatMode = gameScore.get("cheatMode");
gameScore.increment("score");
gameScore.addUnique("skills", "flying");
gameScore.addUnique("skills", "kungfu");
game.set("gameScore", gameScore);
const gameCopy = Game.fromJSON(JSON.parse(JSON.stringify(game)), true);
}
function test_query() {
const gameScore = new GameScore();
const query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.notEqualTo("playerName", "Michael Yabuti");
query.fullText("playerName", "dan", { language: 'en', caseSensitive: false, diacriticSensitive: true });
query.greaterThan("playerAge", 18);
query.limit(10);
query.skip(10);
// Sorts the results in ascending order by the score field
query.ascending("score");
// Sorts the results in descending order by the score field
query.descending("score");
// Restricts to wins < 50
query.lessThan("wins", 50);
// Restricts to wins <= 50
query.lessThanOrEqualTo("wins", 50);
// Restricts to wins > 50
query.greaterThan("wins", 50);
// Restricts to wins >= 50
query.greaterThanOrEqualTo("wins", 50);
// Finds scores from any of Jonathan, Dario, or Shawn
query.containedIn("playerName",
["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]);
// Finds scores from anyone who is neither Jonathan, Dario, nor Shawn
query.notContainedIn("playerName",
["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]);
// Finds objects that have the score set
query.exists("score");
// Finds objects that don't have the score set
query.doesNotExist("score");
query.matchesKeyInQuery("hometown", "city", query);
query.doesNotMatchKeyInQuery("hometown", "city", query);
query.select("score", "playerName");
// Find objects where the array in arrayKey contains 2.
query.equalTo("arrayKey", 2);
// Find objects where the array in arrayKey contains all of the elements 2, 3, and 4.
query.containsAll("arrayKey", [2, 3, 4]);
query.startsWith("name", "Big Daddy's");
query.equalTo("score", gameScore);
query.exists("score");
query.include("score");
query.include(["score.team"]);
// Find objects that match the aggregation pipeline
query.aggregate({
group:{
objectId: '$name'
}
});
// Find objects with distinct key
query.distinct('name');
const testQuery = Parse.Query.or(query, query);
}
class TestCollection extends Parse.Collection<Object> {
constructor(models?: Parse.Object[]) {
super(models);
}
}
function return_a_generic_query(): Parse.Query<Game> {
return new Parse.Query(Game);
}
function return_a_query(): Parse.Query {
return new Parse.Query(Game);
}
function test_collections() {
let collection = new TestCollection();
const query = new Parse.Query(Game);
query.equalTo("temperature", "hot");
query.greaterThan("degreesF", 100);
collection = query.collection();
collection.comparator = (object) => {
return object.get("temperature");
};
collection.add([
{ "name": "Duke" },
{ "name": "Scarlett" }
]);
collection.fetch().then(
(data) => {
},
(error) => {
console.log("Error: " + error.code + " " + error.message);
}
);
const model = collection.at(0);
// Or you can get it by Parse objectId.
const modelAgain = collection.get(model.id);
// Remove "Duke" from the collection.
collection.remove(model);
// Completely replace all items in the collection.
collection.reset([
{ "name": "Hawk" },
{ "name": "Jane" }
]);
}
function test_file() {
const base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE=";
let file = new Parse.File("myfile.txt", { base64: base64 });
const bytes = [0xBE, 0xEF, 0xCA, 0xFE];
file = new Parse.File("myfile.txt", bytes);
file = new Parse.File("myfile.zzz", {}, "image/png");
const src = file.url();
file.save().then(
() => {
// The file has been saved to Parse.
},
(error) => {
// The file either could n ot be read, or could not be saved to Parse.
});
Parse.Cloud.httpRequest({ url: file.url() }).then((response: Parse.Cloud.HttpResponse) => {
// result
});
// TODO: Check
}
function test_analytics() {
const dimensions = {
// Define ranges to bucket data points into meaningful segments
priceRange: '1000-1500',
// Did the user filter the query?
source: 'craigslist',
// Do searches happen more often on weekdays or weekends?
dayType: 'weekday'
};
// Send the dimensions to Parse along with the 'search' event
Parse.Analytics.track('search', dimensions);
const codeString = '404';
Parse.Analytics.track('error', { code: codeString })
}
function test_relation() {
var game1 = new Game();
var game2 = new Game();
new Parse.User().relation("games").query().find().then((g: Game[]) => { });
new Parse.User().relation("games").add(game1)
new Parse.User().relation("games").add([game1, game2])
new Parse.User().relation("games").remove(game1)
new Parse.User().relation("games").remove([game1, game2])
}
function test_user() {
const user = new Parse.User();
user.set("username", "my name");
user.set("password", "my pass");
user.set("email", "email@example.com");
user.signUp(null, { useMasterKey: true });
}
function test_user_acl_roles() {
const user = new Parse.User();
user.set("username", "my name");
user.set("password", "my pass");
user.set("email", "email@example.com");
// other fields can be set just like with Parse.Object
user.set("phone", "415-392-0202");
const currentUser = Parse.User.current();
if (currentUser) {
// do stuff with the user
} else {
// show the signup or login page
}
Parse.User.become("session-token-here").then(function (user) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
const game = new Game();
game.set("score", new GameScore());
game.setACL(new Parse.ACL(Parse.User.current()));
game.save().then((game: Game) => { });
game.save(null, { useMasterKey: true });
game.save({ score: '10' }, { useMasterKey: true }).then(function (game) {
// Update game then revert it to the last saved state.
game.set("score", '20');
game.revert();
}, function (error) {
// The save failed
});
const groupACL = new Parse.ACL();
const userList: Parse.User[] = [Parse.User.current()!];
// userList is an array with the users we are sending this message to.
for (let i = 0; i < userList.length; i++) {
groupACL.setReadAccess(userList[i], true);
groupACL.setWriteAccess(userList[i], true);
}
groupACL.setPublicReadAccess(true);
game.setACL(groupACL);
Parse.User.requestPasswordReset("email@example.com").then(function (data) {
// The current user is now set to user.
}, function (error) {
// The token could not be validated.
});
// By specifying no write privileges for the ACL, we can ensure the role cannot be altered.
const role = new Parse.Role("Administrator", groupACL);
role.getUsers().add(userList[0]);
role.getRoles().add(role);
role.save();
Parse.User.logOut().then(function (data) {
// logged out
});
}
function test_facebook_util() {
Parse.FacebookUtils.init({
appId: 'YOUR_APP_ID', // Facebook App ID
channelUrl: '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
cookie: true, // enable cookies to allow Parse to access the session
xfbml: true // parse XFBML
});
Parse.FacebookUtils.logIn(null, {
success: (user: Parse.User) => {
if (!user.existed()) {
alert("User signed up and logged in through Facebook!");
} else {
alert("User logged in through Facebook!");
}
},
error: (user: Parse.User, error: any) => {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
const user = Parse.User.current()!;
if (!Parse.FacebookUtils.isLinked(user)) {
Parse.FacebookUtils.link(user, null, {
success: (user: any) => {
alert("Woohoo, user logged in with Facebook!");
},
error: (user: any, error: any) => {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
}
Parse.FacebookUtils.unlink(user, {
success: (user: Parse.User) => {
alert("The user is no longer associated with their Facebook account.");
}
});
}
function test_cloud_functions() {
Parse.Cloud.run('hello', {}, {
success: (result: any) => {
// result
},
error: (error: any) => {
}
});
Parse.Cloud.afterDelete('MyCustomClass', (request: Parse.Cloud.AfterDeleteRequest) => {
// result
});
Parse.Cloud.afterSave('MyCustomClass', (request: Parse.Cloud.AfterSaveRequest) => {
// result
});
Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest,
response: Parse.Cloud.BeforeDeleteResponse) => {
// result
});
const CUSTOM_ERROR_INVALID_CONDITION = 1001
const CUSTOM_ERROR_IMMUTABLE_FIELD = 1002
Parse.Cloud.beforeSave('MyCustomClass', (request: Parse.Cloud.BeforeSaveRequest,
response: Parse.Cloud.BeforeSaveResponse) => {
if (request.object.isNew()) {
if (!request.object.has('immutable')) return response.error('Field immutable is required')
} else {
const original = request.original;
if (original == null) { // When the object is not new, request.original must be defined
return response.error(CUSTOM_ERROR_INVALID_CONDITION, 'Original must me defined for an existing object')
}
if (original.get('immutable') !== request.object.get('immutable')) {
return response.error(CUSTOM_ERROR_IMMUTABLE_FIELD, 'This field cannot be changed')
}
}
response.success()
});
Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => {
let query = request.query; // the Parse.Query
let user = request.user; // the user
let isMaster = request.master; // if the query is run with masterKey
let isCount = request.count; // if the query is a count operation (available on parse-server 2.4.0 or up)
let isGet = request.isGet; // if the query is a get operation
// All possible read preferences
request.readPreference = Parse.Cloud.ReadPreferenceOption.Primary
request.readPreference = Parse.Cloud.ReadPreferenceOption.PrimaryPreferred
request.readPreference = Parse.Cloud.ReadPreferenceOption.Secondary
request.readPreference = Parse.Cloud.ReadPreferenceOption.SecondaryPreferred
request.readPreference = Parse.Cloud.ReadPreferenceOption.Nearest
});
}
class PlaceObject extends Parse.Object { }
function test_geo_points() {
const point = new Parse.GeoPoint({ latitude: 40.0, longitude: -30.0 });
const userObject = Parse.User.current()!;
// User's location
const userGeoPoint = userObject.get("location");
// Create a query for places
const query = new Parse.Query(Parse.User);
// Interested in locations near user.
query.near("location", userGeoPoint);
// Limit what could be a lot of points.
query.limit(10);
const southwestOfSF = new Parse.GeoPoint(37.708813, -122.526398);
const northeastOfSF = new Parse.GeoPoint(37.822802, -122.373962);
const query2 = new Parse.Query(PlaceObject);
query2.withinGeoBox("location", southwestOfSF, northeastOfSF);
const query3 = new Parse.Query("PlaceObject").find().then((o: Parse.Object[]) => { });
}
function test_push() {
Parse.Push.send({
channels: ["Gia nts", "Mets"],
data: {
alert: "The Giants won against the Mets 2-3."
}
}, {
success: () => {
// Push was successful
},
error: (error: any) => {
// Handle error
}
});
const query = new Parse.Query(Parse.Installation);
query.equalTo('injuryReports', true);
Parse.Push.send({
where: query, // Set our Installation query
data: {
alert: "Willie Hayes injured by own pop fly."
}
}, {
success: function () {
// Push was successful
},
error: function (error: any) {
// Handle error
}
});
}
function test_view() {
const model = Parse.User.current();
const view = new Parse.View<Parse.User>();
}
function test_promise() {
let resolved = Parse.Promise.as(true);
let rejected = Parse.Promise.error("an error object");
Parse.Promise.when([resolved, rejected]).then(function () {
// success
}, function () {
// failed
});
// Test promise with a query
const query = new Parse.Query('Test');
query.find()
.then(() => {
// success
}).catch(() => {
// error
});
// can check whether an object is a Parse.Promise object or not
Parse.Promise.is(resolved);
}
function test_batch_operations() {
const game1 = new Game()
const game2 = new Game()
const games = [game1, game2]
// Master key
Parse.Object.saveAll(games, { useMasterKey: true })
Parse.Object.destroyAll(games, { useMasterKey: true })
Parse.Object.fetchAll(games, { useMasterKey: true })
Parse.Object.fetchAllIfNeeded(games, { useMasterKey: true })
// Session token
Parse.Object.saveAll(games, { sessionToken: '' })
Parse.Object.destroyAll(games, { sessionToken: '' })
Parse.Object.fetchAll(games, { sessionToken: '' })
Parse.Object.fetchAllIfNeeded(games, { sessionToken: '' })
}
function test_query_subscribe() {
// create new query from Game object type
const query = new Parse.Query(Game);
// create subscription to Game object
const subscription = query.subscribe();
// listen for new Game objects created on Parse server
subscription.on('create', (game: any) => {
console.log(game);
});
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": ["es6", "dom"],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": ["../../"],
"paths": {
"parse": ["parse/v1"],
"parse/*": ["parse/v1/*"]
},
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": ["index.d.ts", "parse-tests.ts"]
}
+81
View File
@@ -0,0 +1,81 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-const-enum": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"use-default-type-parameter": false,
"void-return": false,
"whitespace": false
}
}