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

Add context to object save in JS SDK #730

Merged
merged 10 commits into from
Jul 27, 2020
91 changes: 51 additions & 40 deletions _includes/cloudcode/cloud-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,11 @@ We don't support at the moment job scheduling and highly recommend to use a 3rd

Viewing jobs is supported on parse-dashboard starting version 1.0.19, but you can also query the _JobStatus class with a masterKey call to fetch your recent jobs.

# beforeSave Triggers
# Save Triggers

## Implementing validation
## beforeSave

### Implementing validation

Another reason to run code in the cloud is to enforce a particular data format. For example, you might have both an Android and an iOS app, and you want to validate data for each of those. Rather than writing code once for each client environment, you can write it just once with Cloud Code.

Expand All @@ -192,7 +194,7 @@ If the function throws, the `Review` object will not be saved, and the client wi

One useful tip is that even if your mobile app has many different versions, the same version of Cloud Code applies to all of them. Thus, if you launch an application that doesn't correctly check the validity of input data, you can still fix this problem by adding a validation with `beforeSave`.

## Modifying Objects on Save
### Modifying Objects on Save

In some cases, you don't want to throw out invalid data. You just want to tweak it a bit before saving it. `beforeSave` can handle this case, too. Any adjustment you make to request.object will be saved.

Expand All @@ -208,7 +210,7 @@ Parse.Cloud.beforeSave("Review", (request) => {
});
```

## Predefined Classes
### Predefined Classes
If you want to use `beforeSave` for a predefined class in the Parse JavaScript SDK (e.g. [Parse.User]({{ site.apis.js }}classes/Parse.User.html)), you should not pass a String for the first argument. Instead, you should pass the class itself, for example:

```javascript
Expand All @@ -217,7 +219,7 @@ Parse.Cloud.beforeSave(Parse.User, async (request) => {
})
```

# afterSave Triggers
## afterSave

In some cases, you may want to perform some action, such as a push, after an object has been saved. You can do this by registering a handler with the `afterSave` method. For example, suppose you want to keep track of the number of comments on a blog post. You can do that by writing a function like this:

Expand All @@ -235,15 +237,27 @@ Parse.Cloud.afterSave("Comment", (request) => {
});
```

## Async Behavior
### Async Behavior

In the example above, the client will receive a successful response before the promise in the handler completes, regardless of how the promise resolves. For instance, the client will receive a successful response even if the handler throws an exception. Any errors that occurred while running the handler can be found in the Cloud Code log.

You can use an `afterSave` handler to perform lengthy operations after sending a response back to the client. In order to respond to the client before the `afterSave` handler completes, your handler may not return a promise and your `afterSave` handler may not use async/await.

## Using Request Context
### Predefined Classes

If you want to use `afterSave` for a predefined class in the Parse JavaScript SDK (e.g. [Parse.User]({{ site.apis.js }}classes/Parse.User.html)), you should not pass a String for the first argument. Instead, you should pass the class itself, for example:

```javascript
Parse.Cloud.afterSave(Parse.User, async (request) => {
// code here
})
```

## Context

When saving a `Parse.Object` you may pass a `context` dictionary that is accessible in the Cloud Code Save Triggers. More info in the [JavaScript Guide]({{ site.baseUrl }}/js/guide/#cloud-code-context).

State can be passed from a `beforeSave` handler to an `afterSave` handler in the Request Context. The following example sends emails to users who are being added to a [Parse.Role's users relation](https://parseplatform.org/Parse-SDK-JS/api/2.1.0/Parse.Role.html#getUsers) asynchronously, so the client receives a response before the emails complete sending:
The context is also passed from a `beforeSave` handler to an `afterSave` handler. The following example sends emails to users who are being added to a [Parse.Role's users relation](https://parseplatform.org/Parse-SDK-JS/api/2.1.0/Parse.Role.html#getUsers) asynchronously, so the client receives a response before the emails complete sending:

```javascript
const beforeSave = function beforeSave(request) {
Expand All @@ -268,18 +282,9 @@ const afterSave = function afterSave(request) {
};

```
# Delete Triggers

## Predefined Classes

If you want to use `afterSave` for a predefined class in the Parse JavaScript SDK (e.g. [Parse.User]({{ site.apis.js }}classes/Parse.User.html)), you should not pass a String for the first argument. Instead, you should pass the class itself, for example:

```javascript
Parse.Cloud.afterSave(Parse.User, async (request) => {
// code here
})
```

# beforeDelete Triggers
## beforeDelete

You can run custom Cloud Code before an object is deleted. You can do this with the `beforeDelete` method. For instance, this can be used to implement a restricted delete policy that is more sophisticated than what can be expressed through [ACLs]({{ site.apis.js }}/classes/Parse.ACL.html). For example, suppose you have a photo album app, where many photos are associated with each album, and you want to prevent the user from deleting an album if it still has a photo in it. You can do that by writing a function like this:

Expand All @@ -300,7 +305,7 @@ Parse.Cloud.beforeDelete("Album", (request) => {

If the function throws, the `Album` object will not be deleted, and the client will get an error. Otherwise,the object will be deleted normally.

## Predefined Classes
### Predefined Classes
If you want to use `beforeDelete` for a predefined class in the Parse JavaScript SDK (e.g. [Parse.User]({{ site.apis.js }}classes/Parse.User.html)), you should not pass a String for the first argument. Instead, you should pass the class itself, for example:

```javascript
Expand All @@ -309,7 +314,7 @@ Parse.Cloud.beforeDelete(Parse.User, async (request) => {
})
```

# afterDelete Triggers
## afterDelete

In some cases, you may want to perform some action, such as a push, after an object has been deleted. You can do this by registering a handler with the `afterDelete` method. For example, suppose that after deleting a blog post, you also want to delete all associated comments. You can do that by writing a function like this:

Expand All @@ -329,7 +334,7 @@ The `afterDelete` handler can access the object that was deleted through `reques

The client will receive a successful response to the delete request after the handler terminates, regardless of how the `afterDelete` terminates. For instance, the client will receive a successful response even if the handler throws an exception. Any errors that occurred while running the handler can be found in the Cloud Code log.

## Predefined Classes
### Predefined Classes
If you want to use `afterDelete` for a predefined class in the Parse JavaScript SDK (e.g. [Parse.User]({{ site.apis.js }}classes/Parse.User.html)), you should not pass a String for the first argument. Instead, you should pass the class itself, for example:

```javascript
Expand All @@ -338,11 +343,13 @@ Parse.Cloud.afterDelete(Parse.User, async (request) => {
})
```

# beforeSaveFile Triggers
# File Triggers

## beforeSaveFile

With the `beforeSaveFile` method you can run custom Cloud Code before any file is saved. Returning a new `Parse.File` will save the new file instead of the one sent by the client.

## Examples
### Examples

```javascript
// Changing the file name
Expand All @@ -367,7 +374,7 @@ Parse.Cloud.beforeSaveFile((request) => {
});
```

## Metadata and Tags
### Metadata and Tags

Adding Metadata and Tags to your files allows you to add additional bits of data to the files that are stored within your storage solution (i.e AWS S3). The `beforeSaveFile` hook is a great place to set the metadata and/or tags on your files.

Expand All @@ -382,7 +389,7 @@ Parse.Cloud.beforeSaveFile((request) => {
});
```

# afterSaveFile Triggers
## afterSaveFile

The `afterSaveFile` method is a great way to keep track of all of the files stored in your app. For example:

Expand All @@ -398,7 +405,7 @@ Parse.Cloud.afterSaveFile(async (request) => {
});
```

# beforeDeleteFile Triggers
## beforeDeleteFile

You can run custom Cloud Code before any file gets deleted. For example, lets say you want to add logic that only allows files to be deleted by the user who created it. You could use a combination of the `afterSaveFile` and the `beforeDeleteFile` methods as follows:

Expand All @@ -422,7 +429,7 @@ Parse.Cloud.beforeDeleteFile(async (request) => {
});
```

# afterDeleteFile Triggers
## afterDeleteFile

In the above `beforeDeleteFile` example the `FileObject` collection is used to keep track of saved files in your app. The `afterDeleteFile` trigger is a good place to clean up these objects once a file has been successfully deleted.

Expand All @@ -436,13 +443,15 @@ Parse.Cloud.afterDeleteFile(async (request) => {
});
```

# beforeFind Triggers
# Find Triggers

## beforeFind

*Available only on parse-server cloud code starting 2.2.20*

In some cases you may want to transform an incoming query, adding an additional limit or increasing the default limit, adding extra includes or restrict the results to a subset of keys. You can do so with the `beforeFind` trigger.

## Examples
### Examples

```javascript
// Properties available
Expand Down Expand Up @@ -499,7 +508,7 @@ Parse.Cloud.beforeFind('MyObject2', (req) => {

```

## Predefined Classes
### Predefined Classes

If you want to use `beforeFind` for a predefined class in the Parse JavaScript SDK (e.g. [Parse.User]({{ site.apis.js }}classes/Parse.User.html)), you should not pass a String for the first argument. Instead, you should pass the class itself, for example:

Expand All @@ -509,7 +518,7 @@ Parse.Cloud.beforeFind(Parse.User, async (request) => {
})
```

# afterFind Triggers
## afterFind

*Available only on parse-server cloud code starting 2.2.25*

Expand All @@ -521,7 +530,7 @@ Parse.Cloud.afterFind('MyCustomClass', async (request) => {
})
```

## Predefined Classes
### Predefined Classes

If you want to use `afterFind` for a predefined class in the Parse JavaScript SDK (e.g. [Parse.User]({{ site.apis.js }}classes/Parse.User.html)), you should not pass a String for the first argument. Instead, you should pass the class itself, for example:

Expand All @@ -531,7 +540,9 @@ Parse.Cloud.afterFind(Parse.User, async (request) => {
})
```

# beforeLogin Triggers
# Session Triggers

## beforeLogin

*Available only on parse-server cloud code starting 3.3.0*

Expand All @@ -546,21 +557,21 @@ Parse.Cloud.beforeLogin(async request => {
});
```

## Some considerations to be aware of
### Some considerations to be aware of

- It waits for any promises to resolve
- The user is not available on the request object - the user has not yet been provided a session until after beforeLogin is successfully completed
- Like `afterSave` on `Parse.User`, it will not save mutations to the user unless explicitly saved

### The trigger will run...
#### The trigger will run...
- On username & password logins
- On `authProvider` logins

### The trigger won't run...
#### The trigger won't run...
- On sign up
- If the login credentials are incorrect

# afterLogout Triggers
## afterLogout

*Available only on parse-server cloud code starting 3.10.0*

Expand All @@ -575,10 +586,10 @@ Parse.Cloud.afterLogout(async request => {
});
```

## Some considerations to be aware of
### Some considerations to be aware of
- Like with `afterDelete` triggers, the `_Session` object that is contained in the request has already been deleted.

### The trigger will run...
#### The trigger will run...
- when the user logs out and a `_Session` object was deleted

### The trigger won't run...
Expand Down
25 changes: 25 additions & 0 deletions _includes/js/objects.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,31 @@ teamMember.save(null, { cascadeSave: false });

```

### Cloud Code context

*Requires Parse Server 4.3.0+*

You may pass a `context` dictionary that is accessible in Cloud Code `beforeSave` and `afterSave` triggers for that `Parse.Object`. This is useful if you want to condition certain operations in Cloud Code triggers on ephemeral information that should not be saved with the `Parse.Object` in the database. The context is ephemeral in the sense that it vanishes after the Cloud Code triggers for that particular `Parse.Object` have executed. For example:

```javascript
var TeamMember = Parse.Object.extend("TeamMember");
var teamMember = new TeamMember();
teamMember.set("team", "A");

var context = { notifyTeam: false };
await teamMember.save(null, { context: context });
```

The context is then accessible in Cloud Code:

```javascript
Parse.Cloud.afterSave("TeamMember", async (req) => {
var notifyTeam = req.context.notifyTeam;
if (notifyTeam) {
// Notify team about new member.
}
});
```

## Retrieving Objects

Expand Down