Skip to content

feat: Add a new beforeLiveQueryEvent trigger #9445

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

Open
wants to merge 4 commits into
base: alpha
Choose a base branch
from

Conversation

codeKonami
Copy link

@codeKonami codeKonami commented Nov 19, 2024

Pull Request

Issue

Closes: #9431

Approach

I added a beforeLiveQueryEvent trigger which allows the user to modify the updated object before it is passed to the LiveQuery server (via PubSub). It is a cloned version of the object so it won't modify the one passed to the afterSave trigger.

I've added an option which I'm not really convinced. You can set the context of the request to req.context.preventLiveQuery === true to prevent the publish to be made by the Parse Server and so limiting some network and CPU consumption depending on some business logic.

Tasks

  • Add tests
  • Add changes to documentation (guides, repository pages, code comments)
  • Add security check
  • Add new Parse Error codes to Parse JS SDK

Summary by CodeRabbit

  • New Features

    • Introduced support for registering "before live query event" triggers, allowing custom logic to run before live query events are published.
    • Added the ability to prevent specific live query events from being sent by setting a context flag in the trigger.
  • Bug Fixes

    • Improved context handling for triggers to ensure consistent behavior during live query events.
  • Tests

    • Added comprehensive tests to verify the behavior and effects of the new "before live query event" triggers.
Copy link

Thanks for opening this pull request!

@mtrezza
Copy link
Member

mtrezza commented Apr 7, 2025

@codeKonami please let us know when this is ready for review and change the PR state.

@codeKonami codeKonami marked this pull request as ready for review April 15, 2025 21:39
@codeKonami
Copy link
Author

@codeKonami please let us know when this is ready for review and change the PR state.

The code is ready, I'd be interested to have your opinion on the approach before going further on documentation and probably more unit tests.

@mtrezza
Copy link
Member

mtrezza commented May 3, 2025

@coderabbitai review

Copy link

coderabbitai bot commented May 3, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented May 3, 2025

📝 Walkthrough

Walkthrough

The changes introduce a new Parse Server trigger called beforeLiveQueryEvent. This trigger allows developers to execute custom logic before a LiveQuery event is published. The implementation includes a new registration method in the Parse Cloud SDK, integration of the new trigger type into the trigger handling system, and updates to the LiveQuery publishing flow to support conditional event suppression based on the trigger's outcome. Comprehensive tests have been added to verify correct triggering, context handling, object mutation, and the ability to prevent LiveQuery events.

Changes

File(s) Change Summary
spec/ParseLiveQuery.spec.js Added new test cases for beforeLiveQueryEvent trigger, testing execution, context, mutation, and event prevention.
src/RestWrite.js Refactored runAfterSaveTrigger to async; integrated beforeLiveQueryEvent trigger before LiveQuery notification.
src/cloud-code/Parse.Cloud.js Added ParseCloud.beforeLiveQueryEvent method for registering the new trigger.
src/triggers.js Added beforeEvent trigger type; updated context handling in trigger execution to support the new trigger.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ParseServer
    participant CloudCode
    participant LiveQueryServer

    Client->>ParseServer: Save or update object
    ParseServer->>CloudCode: Run beforeLiveQueryEvent trigger (if defined)
    alt beforeLiveQueryEvent sets preventLiveQuery
        CloudCode-->>ParseServer: preventLiveQuery = true
        ParseServer-->>LiveQueryServer: (No notification sent)
    else beforeLiveQueryEvent allows event
        CloudCode-->>ParseServer: allow event
        ParseServer->>LiveQueryServer: Notify LiveQuery event
    end
    ParseServer->>CloudCode: Run afterSave trigger (if defined)
    ParseServer-->>Client: Respond to save/update
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement a beforeLiveQueryEvent trigger to allow conditional suppression of LiveQuery event publishing (#9431)
Provide a registration method for the new trigger in the Cloud Code SDK (#9431)
Integrate the new trigger into the event publishing flow and context handling (#9431)
Add tests verifying trigger execution, context mutation, and event suppression (#9431)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.
@parseplatformorg
Copy link
Contributor

🎉 Snyk checks have passed. No issues have been found so far.

security/snyk check is complete. No issues have been found. (View Details)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (2)
src/cloud-code/Parse.Cloud.js (1)

631-631: Fix indentation issue.

There's an extra space at the beginning of this line causing an ESLint error.

-  ParseCloud.beforeLiveQueryEvent = function (parseClass, handler, validationHandler) {
+ ParseCloud.beforeLiveQueryEvent = function (parseClass, handler, validationHandler) {
🧰 Tools
🪛 ESLint

[error] 631-631: Expected indentation of 0 spaces but found 1.

(indent)

src/RestWrite.js (1)

1667-1675: Trigger type name may be inconsistent with public API

The new hook is exposed to users as beforeLiveQueryEvent, yet the internal lookup uses triggers.Types.beforeEvent.
If beforeEvent is not aliased to beforeLiveQueryEvent inside triggers.js, user-registered callbacks will never be found and the feature will appear broken.

Please verify that:

  1. triggers.Types.beforeEvent is exported under the documented name, or
  2. This lookup is switched to beforeLiveQueryEvent.

Otherwise the hook will never fire.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 560beea and 82ea402.

📒 Files selected for processing (4)
  • spec/ParseLiveQuery.spec.js (1 hunks)
  • src/RestWrite.js (2 hunks)
  • src/cloud-code/Parse.Cloud.js (1 hunks)
  • src/triggers.js (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
spec/ParseLiveQuery.spec.js (2)
spec/helper.js (3)
  • reconfigureServer (171-205)
  • Parse (4-4)
  • TestObject (257-259)
spec/ParseLiveQueryServer.spec.js (6)
  • Parse (1-1)
  • query (293-299)
  • query (330-336)
  • query (377-383)
  • query (1102-1108)
  • query (1152-1158)
🪛 ESLint
src/cloud-code/Parse.Cloud.js

[error] 631-631: Expected indentation of 0 spaces but found 1.

(indent)

spec/ParseLiveQuery.spec.js

[error] 1312-1312: 'it' is not defined.

(no-undef)


[error] 1313-1313: 'reconfigureServer' is not defined.

(no-undef)


[error] 1324-1324: 'expect' is not defined.

(no-undef)


[error] 1325-1325: 'expect' is not defined.

(no-undef)


[error] 1328-1328: 'TestObject' is not defined.

(no-undef)


[error] 1331-1331: 'expect' is not defined.

(no-undef)


[error] 1332-1332: 'done' is not defined.

(no-undef)


[error] 1335-1335: 'TestObject' is not defined.

(no-undef)


[error] 1340-1340: 'it' is not defined.

(no-undef)


[error] 1341-1341: 'reconfigureServer' is not defined.

(no-undef)


[error] 1349-1349: 'TestObject' is not defined.

(no-undef)


[error] 1354-1354: 'expect' is not defined.

(no-undef)


[error] 1357-1357: 'expect' is not defined.

(no-undef)


[error] 1361-1361: 'expect' is not defined.

(no-undef)


[error] 1362-1362: 'expect' is not defined.

(no-undef)


[error] 1363-1363: 'expect' is not defined.

(no-undef)


[error] 1366-1366: 'TestObject' is not defined.

(no-undef)


[error] 1369-1369: 'expect' is not defined.

(no-undef)


[error] 1377-1377: 'it' is not defined.

(no-undef)


[error] 1378-1378: 'reconfigureServer' is not defined.

(no-undef)


[error] 1389-1389: 'expect' is not defined.

(no-undef)


[error] 1395-1395: 'TestObject' is not defined.

(no-undef)


[error] 1398-1398: 'fail' is not defined.

(no-undef)


[error] 1401-1401: 'TestObject' is not defined.

(no-undef)


[error] 1406-1406: 'it' is not defined.

(no-undef)


[error] 1407-1407: 'reconfigureServer' is not defined.

(no-undef)


[error] 1415-1415: 'TestObject' is not defined.

(no-undef)


[error] 1420-1420: 'expect' is not defined.

(no-undef)


[error] 1426-1426: 'TestObject' is not defined.

(no-undef)


[error] 1429-1429: 'fail' is not defined.

(no-undef)

🔇 Additional comments (4)
src/cloud-code/Parse.Cloud.js (1)

607-641: Well-implemented new trigger function!

The new beforeLiveQueryEvent hook follows the established pattern of other trigger functions in the codebase. It's properly integrated with the trigger system and includes comprehensive documentation.

🧰 Tools
🪛 ESLint

[error] 631-631: Expected indentation of 0 spaces but found 1.

(indent)

src/triggers.js (3)

17-17: Appropriately added new trigger type.

The beforeEvent trigger type has been correctly added to the Types object.


282-284: Correct integration with context handling.

The beforeEvent trigger type has been properly integrated with the context copying mechanism in the getRequestObject function.


890-892: Properly integrated with context merging.

The beforeEvent trigger type has been correctly added to the condition that merges the request context back into the external context, which is essential for the preventLiveQuery functionality.

Comment on lines +1419 to +1424
Parse.Cloud.beforeLiveQueryEvent('TestObject', async req => {
expect(req.object.get('foo')).toBe('baz');
if (req.object.get('foo') === 'baz') {
req.context.preventLiveQuery === true;
}
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix critical bug in preventLiveQuery logic.

Same issue as in the previous test - you're using a comparison operator (===) instead of an assignment operator (=).

-      if (req.object.get('foo') === 'baz') {
-        req.context.preventLiveQuery === true;
+      if (req.object.get('foo') === 'baz') {
+        req.context.preventLiveQuery = true;
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

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

[error] 1420-1420: 'expect' is not defined.

(no-undef)

🤖 Prompt for AI Agents (early access)
In spec/ParseLiveQuery.spec.js around lines 1419 to 1424, the code mistakenly uses the comparison operator (===) instead of the assignment operator (=) when setting req.context.preventLiveQuery. Change req.context.preventLiveQuery === true to req.context.preventLiveQuery = true to correctly assign the value and fix the preventLiveQuery logic.
Comment on lines +1388 to +1393
Parse.Cloud.beforeLiveQueryEvent('TestObject', req => {
expect(req.object.get('foo')).toBe('bar');
if (req.object.get('foo') === 'bar') {
req.context.preventLiveQuery === true;
}
})
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix critical bug in preventLiveQuery logic.

You're using a comparison operator (===) instead of an assignment operator (=), which means you're comparing the value rather than setting it. This would cause the filtering functionality to fail.

-      if (req.object.get('foo') === 'bar') {
-        req.context.preventLiveQuery === true;
+      if (req.object.get('foo') === 'bar') {
+        req.context.preventLiveQuery = true;
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

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

[error] 1389-1389: 'expect' is not defined.

(no-undef)

🤖 Prompt for AI Agents (early access)
In spec/ParseLiveQuery.spec.js around lines 1388 to 1393, replace the comparison operator (===) with the assignment operator (=) when setting req.context.preventLiveQuery to true. This change will correctly assign the value and enable the intended filtering functionality.
Comment on lines +1312 to +1338
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();
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix test callback handling.

This test is using done() on line 1332, but the function doesn't receive the done parameter. The test should either:

  1. Receive done as a parameter and call it at the end, or
  2. Return a promise or use async/await properly
-  it('test beforeLiveQueryEvent ran while creating an object', async function () {
+  it('test beforeLiveQueryEvent ran while creating an object', async function (done) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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 creating an object', async function (done) {
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();
});
🧰 Tools
🪛 ESLint

[error] 1312-1312: 'it' is not defined.

(no-undef)


[error] 1313-1313: 'reconfigureServer' is not defined.

(no-undef)


[error] 1324-1324: 'expect' is not defined.

(no-undef)


[error] 1325-1325: 'expect' is not defined.

(no-undef)


[error] 1328-1328: 'TestObject' is not defined.

(no-undef)


[error] 1331-1331: 'expect' is not defined.

(no-undef)


[error] 1332-1332: 'done' is not defined.

(no-undef)


[error] 1335-1335: 'TestObject' is not defined.

(no-undef)

🤖 Prompt for AI Agents (early access)
In spec/ParseLiveQuery.spec.js around lines 1312 to 1338, the test uses done() without receiving done as a parameter, causing callback handling issues. Fix this by adding done as a parameter to the test function and calling done() inside the subscription event handler after assertions, or refactor the test to properly use async/await and return a promise without using done().
Comment on lines +1677 to +1686
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
);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Await the schema call to avoid silent LiveQuery failures

this.config.database.loadSchema() returns a promise, but the surrounding async function does not await or return it.
If the DB lookup rejects (e.g. transient connectivity, schema inconsistency) the rejection becomes an unhandled promise, the catch in the caller never fires and LiveQuery delivery silently fails.

-      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
-        );
-      });
+      const schemaController = await this.config.database.loadSchema();
+      // Notify LiveQueryServer if possible
+      const perms = schemaController.getClassLevelPermissions(publishedObject.className);
+      this.config.liveQueryController.onAfterSave(
+        publishedObject.className,
+        publishedObject,
+        originalObject,
+        perms
+      );

This keeps the method “fire-and-forget” semantics for LiveQuery success but still propagates unexpected errors up the promise chain for proper logging / retries.
Please consider the change or add an explicit .catch() to prevent unhandled rejections.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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
);
});
const schemaController = await this.config.database.loadSchema();
// Notify LiveQueryServer if possible
const perms = schemaController.getClassLevelPermissions(publishedObject.className);
this.config.liveQueryController.onAfterSave(
publishedObject.className,
publishedObject,
originalObject,
perms
);
🤖 Prompt for AI Agents (early access)
In src/RestWrite.js around lines 1677 to 1686, the call to this.config.database.loadSchema() returns a promise that is neither awaited nor returned, causing unhandled promise rejections if it fails. To fix this, modify the code to either await the loadSchema() call or return the promise chain, and add a .catch() handler to properly handle and propagate errors, ensuring that any failures in loading the schema do not silently fail and are logged or retried as needed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants