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 trigger beforeUnsubscribe for LiveQuery #7419

Open
wants to merge 8 commits into
base: alpha
Choose a base branch
from
Open
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
39 changes: 39 additions & 0 deletions spec/ParseLiveQuery.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -800,6 +800,45 @@ describe('ParseLiveQuery', function () {
await object.save();
});

it('can handle select beforeUnsubscribe trigger', async done => {
await reconfigureServer({
liveQuery: {
classNames: ['TestObject'],
},
startLiveQueryServer: true,
verbose: false,
silent: true,
});
const user = new Parse.User();
user.setUsername('username');
user.setPassword('password');
await user.signUp();

Parse.Cloud.beforeSubscribe(TestObject, req => {
expect(req.requestId).toBe(1);
expect(req.user).toBeDefined();
});

Parse.Cloud.beforeUnsubscribe(TestObject, req => {
expect(req.requestId).toBe(1);
expect(req.user).toBeDefined();
sadortun marked this conversation as resolved.
Show resolved Hide resolved
expect(req.user.get('username')).toBe('username');
done();
});

const object = new TestObject();
await object.save();

const query = new Parse.Query(TestObject);
query.equalTo('objectId', object.id);
const subscription = await query.subscribe();

object.set({ foo: 'bar', yolo: 'abc' });
await object.save();

await subscription.unsubscribe();
});

it('LiveQuery with ACL', async () => {
await reconfigureServer({
liveQuery: {
Expand Down
28 changes: 25 additions & 3 deletions src/LiveQuery/ParseLiveQueryServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -968,7 +968,7 @@ class ParseLiveQueryServer {
this._handleSubscribe(parseWebsocket, request);
}

_handleUnsubscribe(parseWebsocket: any, request: any, notifyClient: boolean = true): any {
async _handleUnsubscribe(parseWebsocket: any, request: any, notifyClient: boolean = true): any {
// If we can not find this client, return error to client
if (!Object.prototype.hasOwnProperty.call(parseWebsocket, 'clientId')) {
Client.pushError(
Expand Down Expand Up @@ -1015,11 +1015,33 @@ class ParseLiveQueryServer {
return;
}

const subscription = subscriptionInfo.subscription;
const className = subscription.className;
const trigger = getTrigger(className, 'beforeUnsubscribe', Parse.applicationId);
if (trigger) {
const auth = await this.getAuthFromClient(client, request.requestId, request.sessionToken);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the other uses, getAuthFromClient is wrapped in the try / catch block. I don't think it throws, but could you add it to the try / catch, or add a test case for beforeUnsubscribe without the user.signUp?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sadortun Could you address this comment, then I believe this should be good to merge.

if (auth && auth.user) {
request.user = auth.user;
}

request.sessionToken = subscriptionInfo.sessionToken;
request.useMasterKey = client.hasMasterKey;
request.installationId = client.installationId;

try {
await runTrigger(trigger, `beforeUnsubscribe.${className}`, request, auth);
} catch (error) {
Client.pushError(parseWebsocket, error.code || Parse.Error.SCRIPT_FAILED, error.message || error, false);
logger.error(
`Failed running beforeUnsubscribe for session ${request.sessionToken} with:\n Error: ` +
JSON.stringify(error)
);
}
}

// Remove subscription from client
client.deleteSubscriptionInfo(requestId);
// Remove client from subscription
const subscription = subscriptionInfo.subscription;
const className = subscription.className;
subscription.deleteClientSubscription(parseWebsocket.clientId, requestId);
// If there is no client which is subscribing this subscription, remove it from subscriptions
const classSubscriptions = this.subscriptions.get(className);
Expand Down
36 changes: 36 additions & 0 deletions src/cloud-code/Parse.Cloud.js
Original file line number Diff line number Diff line change
Expand Up @@ -729,6 +729,42 @@ ParseCloud.onLiveQueryEvent = function (handler) {
triggers.addLiveQueryEventHandler(handler, Parse.applicationId);
};

/**
* Registers a before live query subscription function.
*
* **Available in Cloud Code only.**
*
* If you want to use beforeUnsubscribe for a predefined class in the Parse JavaScript SDK (e.g. {@link Parse.User}), you should pass the class itself and not the String for arg1.
* ```
* Parse.Cloud.beforeUnsubscribe('MyCustomClass', (request) => {
* // code here
* }, (request) => {
* // validation code here
* });
*
* Parse.Cloud.beforeUnsubscribe(Parse.User, (request) => {
* // code here
* }, { ...validationObject });
*```
*
* @method beforeUnsubscribe
* @name Parse.Cloud.beforeUnsubscribe
* @param {(String|Parse.Object)} arg1 The Parse.Object subclass to register the before subscription function for. This can instead be a String that is the className of the subclass.
* @param {Function} func The function to run before a subscription. 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.beforeUnsubscribe = function (parseClass, handler, validationHandler) {
sadortun marked this conversation as resolved.
Show resolved Hide resolved
validateValidator(validationHandler);
const className = triggers.getClassName(parseClass);
triggers.addTrigger(
triggers.Types.beforeUnsubscribe,
className,
handler,
Parse.applicationId,
validationHandler
);
};

/**
* Registers an after live query server event function.
*
Expand Down
1 change: 1 addition & 0 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',
beforeUnsubscribe: 'beforeUnsubscribe',
afterEvent: 'afterEvent',
};

Expand Down
Loading