Skip to content

Commit

Permalink
Merge pull request #12814 from Automattic/IslandRhythms/$locals-demo
Browse files Browse the repository at this point in the history
added tutorial to getters-setters
  • Loading branch information
vkarpov15 committed Dec 19, 2022
2 parents 7fbb440 + b50148e commit d0bf353
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
13 changes: 13 additions & 0 deletions docs/tutorials/getters-setters.md
Expand Up @@ -70,6 +70,19 @@ below.
[require:getters/setters.*setters.*update skip]
```

## Passing Parameters using `$locals`

You can't pass parameters to your getter and setter functions like you do to normal function calls.
To configure or pass additional properties to your getters and setters, you can use the document's `$locals` property.

The `$locals` property is the preferred place to store any program-defined data on your document without conflicting with schema-defined properties.
In your getter and setter functions, `this` is the document being accessed, so you set properties on `$locals` and then access those properties in your getters examples.
For example, the following shows how you can use `$locals` to configure the language for a custom getter that returns a string in different languages.

```javascript
[require:getters/setters.*localization.*locale]
```

Differences vs ES6 Getters/Setters
----------------------------------

Expand Down
49 changes: 49 additions & 0 deletions test/docs/getters-setters.test.js
Expand Up @@ -174,4 +174,53 @@ describe('getters/setters', function() {
// acquit:ignore:end
});
});
describe('localization', function() {
it('locale', async function() {
const internationalizedStringSchema = new Schema({
en: String,
es: String
});

const ingredientSchema = new Schema({
// Instead of setting `name` to just a string, set `name` to a map
// of language codes to strings.
name: {
type: internationalizedStringSchema,
// When you access `name`, pull the document's locale
get: function(value) {
return value[this.$locals.language || 'en'];
}
}
});

const recipeSchema = new Schema({
ingredients: [{ type: mongoose.ObjectId, ref: 'Ingredient' }]
});

const Ingredient = mongoose.model('Ingredient', ingredientSchema);
const Recipe = mongoose.model('Recipe', recipeSchema);

// Create some sample data
const { _id } = await Ingredient.create({
name: {
en: 'Eggs',
es: 'Huevos'
}
});
await Recipe.create({ ingredients: [_id] });

// Populate with setting `$locals.language` for internationalization
const language = 'es';
const recipes = await Recipe.find().populate({
path: 'ingredients',
transform: function(doc) {
doc.$locals.language = language;
return doc;
}
});

// Gets the ingredient's name in Spanish `name.es`
assert.equal(recipes[0].ingredients[0].name, 'Huevos'); // 'Huevos'
});
})
});

0 comments on commit d0bf353

Please sign in to comment.