Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add a new beforeLiveQueryEvent trigger #9445

Draft
wants to merge 3 commits into
base: alpha
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions spec/ParseLiveQuery.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1230,4 +1230,128 @@ describe('ParseLiveQuery', function () {
await new Promise(resolve => setTimeout(resolve, 100));
expect(createSpy).toHaveBeenCalledTimes(1);
});

it('test beforeLiveQueryEvent ran while creating an object', async function () {
await reconfigureServer({
liveQuery: {
classNames: ['TestObject'],
},
startLiveQueryServer: true,
verbose: false,
silent: true,
});


Parse.Cloud.beforeLiveQueryEvent('TestObject', req => {
expect(req.user).toBeUndefined();
expect(req.object.get('foo')).toBe('bar');
})

const query = new Parse.Query(TestObject);
const subscription = await query.subscribe();
subscription.on('create', object => {
expect(object.get('foo')).toBe('bar');
done();
});

const object = new TestObject();
object.set('foo', 'bar');
await object.save();
});

it('test beforeLiveQueryEvent ran while updating an object', async function (done) {
await reconfigureServer({
liveQuery: {
classNames: ['TestObject'],
},
startLiveQueryServer: true,
verbose: false,
silent: true,
});
const object = new TestObject();
object.set('foo', 'bar');
await object.save();

Parse.Cloud.afterSave('TestObject', async req => {
expect(req.object.get('foo')).toBe('baz');
})
Parse.Cloud.beforeLiveQueryEvent('TestObject', async req => {
expect(req.object.get('foo')).toBe('baz');
req.object.set('foo', 'rebaz');
})
Parse.Cloud.afterLiveQueryEvent('TestObject', req => {
expect(req.event).toBe('update');
expect(req.user).toBeUndefined();
expect(req.object.get('foo')).toBe('rebaz');
});

const query = new Parse.Query(TestObject);
const subscription = await query.subscribe();
subscription.on('update', object => {
expect(object.get('foo')).toBe('rebaz');
done();
});

object.set('foo', 'baz')
await object.save();
});

it('test beforeLiveQueryEvent should filter specific object creation', async function () {
await reconfigureServer({
liveQuery: {
classNames: ['TestObject'],
},
startLiveQueryServer: true,
verbose: false,
silent: true,
});


Parse.Cloud.beforeLiveQueryEvent('TestObject', req => {
expect(req.object.get('foo')).toBe('bar');
if (req.object.get('foo') === 'bar') {
req.context.preventLiveQuery === true;
}
})

const query = new Parse.Query(TestObject).equalTo('foo', 'bar');
const subscription = await query.subscribe();
subscription.on('create', () => {
fail('create should not have been called.');
});

const object = new TestObject();
object.set('foo', 'bar');
await object.save();
});

it('test beforeLiveQueryEvent should filter specific object update', async function () {
await reconfigureServer({
liveQuery: {
classNames: ['TestObject'],
},
startLiveQueryServer: true,
verbose: false,
silent: true,
});
const object = new TestObject();
object.set('foo', 'bar');
await object.save();

Parse.Cloud.beforeLiveQueryEvent('TestObject', async req => {
expect(req.object.get('foo')).toBe('baz');
if (req.object.get('foo') === 'baz') {
req.context.preventLiveQuery === true;
}
})

const query = new Parse.Query(TestObject).equalTo('foo', 'baz');
const subscription = await query.subscribe();
subscription.on('update', object => {
fail('update should not have been called.');
});

object.set('foo', 'baz')
await object.save();
});
});
34 changes: 22 additions & 12 deletions src/RestWrite.js
Original file line number Diff line number Diff line change
Expand Up @@ -1627,7 +1627,7 @@ RestWrite.prototype.runDatabaseOperation = function () {
};

// Returns nothing - doesn't wait for the trigger.
RestWrite.prototype.runAfterSaveTrigger = function () {
RestWrite.prototype.runAfterSaveTrigger = async function () {
if (!this.response || !this.response.response || this.runOptions.many) {
return;
}
Expand All @@ -1642,21 +1642,31 @@ RestWrite.prototype.runAfterSaveTrigger = function () {
if (!hasAfterSaveHook && !hasLiveQuery) {
return Promise.resolve();
}

const { originalObject, updatedObject } = this.buildParseObjects();
updatedObject._handleSaveResponse(this.response.response, this.response.status || 200);

if (hasLiveQuery) {
this.config.database.loadSchema().then(schemaController => {
// Notify LiveQueryServer if possible
const perms = schemaController.getClassLevelPermissions(updatedObject.className);
this.config.liveQueryController.onAfterSave(
updatedObject.className,
updatedObject,
originalObject,
perms
);
});
const hasBeforeEventHook = triggers.triggerExists(
this.className,
triggers.Types.beforeEvent,
this.config.applicationId
);
const publishedObject = updatedObject.clone();
if (hasBeforeEventHook) {
await triggers.maybeRunTrigger(triggers.Types.beforeEvent, this.auth, publishedObject, originalObject, this.config, this.context);
}
if (this.context.preventLiveQuery !== true) {
this.config.database.loadSchema().then(schemaController => {
// Notify LiveQueryServer if possible
const perms = schemaController.getClassLevelPermissions(publishedObject.className);
this.config.liveQueryController.onAfterSave(
publishedObject.className,
publishedObject,
originalObject,
perms
);
});
}
}
if (!hasAfterSaveHook) {
return Promise.resolve();
Expand Down
37 changes: 37 additions & 0 deletions src/cloud-code/Parse.Cloud.js
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,43 @@ ParseCloud.beforeSubscribe = function (parseClass, handler, validationHandler) {
);
};

/**
* Registers a before live query event function.
*
* **Available in Cloud Code only.**
*
* If you want to use beforeLiveQueryEvent for a predefined class in the Parse JavaScript SDK (e.g. {@link Parse.User} or {@link Parse.File}), you should pass the class itself and not the String for arg1.
* ```
* Parse.Cloud.beforeLiveQueryEvent('MyCustomClass', (request) => {
* // code here
* }, (request) => {
* // validation code here
* });
*
* Parse.Cloud.beforeLiveQueryEvent(Parse.User, (request) => {
* // code here
* }, { ...validationObject });
*```
*
* @method beforeLiveQueryEvent
* @name Parse.Cloud.beforeLiveQueryEvent
* @param {(String|Parse.Object)} arg1 The Parse.Object subclass to register the before live query event function for. This can instead be a String that is the className of the subclass.
* @param {Function} func The function to run before a live query event (publish) is made. This function can be async and should take one parameter, a {@link Parse.Cloud.TriggerRequest}.
* @param {(Object|Function)} validator An optional function to help validating cloud code. This function can be an async function and should take one parameter a {@link Parse.Cloud.TriggerRequest}, or a {@link Parse.Cloud.ValidatorObject}.
*/
ParseCloud.beforeLiveQueryEvent = function (parseClass, handler, validationHandler) {
validateValidator(validationHandler);
const className = triggers.getClassName(parseClass);
triggers.addTrigger(
triggers.Types.beforeEvent,
className,
handler,
Parse.applicationId,
validationHandler
);
};


ParseCloud.onLiveQueryEvent = function (handler) {
triggers.addLiveQueryEventHandler(handler, Parse.applicationId);
};
Expand Down
7 changes: 5 additions & 2 deletions src/triggers.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const Types = {
afterFind: 'afterFind',
beforeConnect: 'beforeConnect',
beforeSubscribe: 'beforeSubscribe',
beforeEvent: 'beforeEvent',
afterEvent: 'afterEvent',
};

Expand Down Expand Up @@ -278,7 +279,8 @@ export function getRequestObject(
triggerType === Types.afterDelete ||
triggerType === Types.beforeLogin ||
triggerType === Types.afterLogin ||
triggerType === Types.afterFind
triggerType === Types.afterFind ||
triggerType === Types.beforeEvent
) {
// Set a copy of the context on the request object.
request.context = Object.assign({}, context);
Expand Down Expand Up @@ -885,7 +887,8 @@ export function maybeRunTrigger(
triggerType === Types.beforeSave ||
triggerType === Types.afterSave ||
triggerType === Types.beforeDelete ||
triggerType === Types.afterDelete
triggerType === Types.afterDelete ||
triggerType === Types.beforeEvent
) {
Object.assign(context, request.context);
}
Expand Down