chunk_id stringlengths 36 36 | source stringclasses 35
values | source_url stringlengths 0 290 | upstream_license stringclasses 1
value | document_id stringlengths 36 36 | chunk_index int64 0 324k | retrieved_at stringclasses 2
values | chunker_version stringclasses 4
values | content_hash stringlengths 15 64 | content stringlengths 50 44.7k | namespace stringclasses 9
values | source_name stringclasses 35
values | raw_text stringlengths 50 44.7k | cleaned_text stringlengths 50 44.7k | tags stringclasses 49
values | collection_name stringclasses 11
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e241bd85-8842-4844-aab2-a5b0de0de696 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-factories.md | unknown | 3a45a7c9-4584-49eb-aa48-e17cc25525c8 | 2 | SemanticChunker@1.0.0 | abbb404c30c59b5fa560a0e2da82b3691be3d8c3face19cdcaee0fd5f2a30073 | [Directory structure > Fixtures & Factories]
## Fixtures & Factories
In the world of testing, we often need to create **mock data** to test our code. This is often done with **fixtures**, static pieces of data that we can use to test our code. However, fixtures can be cumbersome to maintain, especially as our objects... | unknown | unknown | [Directory structure > Fixtures & Factories]
## Fixtures & Factories
In the world of testing, we often need to create **mock data** to test our code. This is often done with **fixtures**, static pieces of data that we can use to test our code. However, fixtures can be cumbersome to maintain, especially as our objects... | [Directory structure > Fixtures & Factories]
## Fixtures & Factories
In the world of testing, we often need to create **mock data** to test our code. This is often done with **fixtures**, static pieces of data that we can use to test our code. However, fixtures can be cumbersome to maintain, especially as our objects... | code_snippets | ||
e67c8d68-29f2-4ade-93b9-e254d6bb1432 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-factories.md | unknown | 3a45a7c9-4584-49eb-aa48-e17cc25525c8 | 22 | SemanticChunker@1.0.0 | 62334df6d7e34240a0bdc5acfb1677fd5a8ff06b99bcca662bb714b7dd4d65f6 | [Directory structure > Addendum: Code summary]
```js title="src/models/post.js"
import Model from '#src/core/model.js';
import Author from '#src/models/author.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this);
}
constructor(data) {
super(data);
t... | unknown | unknown | [Directory structure > Addendum: Code summary]
```js title="src/models/post.js"
import Model from '#src/core/model.js';
import Author from '#src/models/author.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this);
}
constructor(data) {
super(data);
t... | [Directory structure > Addendum: Code summary]
```js title="src/models/post.js"
import Model from '#src/core/model.js';
import Author from '#src/models/author.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this);
}
constructor(data) {
super(data);
t... | code_snippets | ||
f7d2609d-4fdb-4f0a-b15c-2bf0a6818135 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-factories.md | unknown | 3a45a7c9-4584-49eb-aa48-e17cc25525c8 | 17 | SemanticChunker@1.0.0 | 0443439141ed7b421fe3c0c58e2e35158c20e5e83ace17a51f04322d2dee75d1 | [Directory structure > Conclusion]
## Conclusion
We've come a long way in this series. We've built **models**, **queries**, **scopes**, **serialization**, and now **factories**. This latest system allows us to easily create complex objects for our tests, and we've even added sequences to generate unique values for ou... | unknown | unknown | [Directory structure > Conclusion]
## Conclusion
We've come a long way in this series. We've built **models**, **queries**, **scopes**, **serialization**, and now **factories**. This latest system allows us to easily create complex objects for our tests, and we've even added sequences to generate unique values for ou... | [Directory structure > Conclusion]
## Conclusion
We've come a long way in this series. We've built **models**, **queries**, **scopes**, **serialization**, and now **factories**. This latest system allows us to easily create complex objects for our tests, and we've even added sequences to generate unique values for ou... | code_snippets | ||
fea9ffcb-ba31-474e-b4fa-c47ac7791014 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-factories.md | unknown | 3a45a7c9-4584-49eb-aa48-e17cc25525c8 | 10 | SemanticChunker@1.0.0 | 811945d193ec9399158fa5520b8289c7edb76cba8c83fd137197921e1b5bc4de | [The Factory class > Convenience methods]
### Convenience methods
As you're well aware by this point, convenience methods are a staple of my coding style. I definitely dislike having to find the appropriate factory to call every time I need to create an object. I'd much rather call a method on the `Factory` class its... | unknown | unknown | [The Factory class > Convenience methods]
### Convenience methods
As you're well aware by this point, convenience methods are a staple of my coding style. I definitely dislike having to find the appropriate factory to call every time I need to create an object. I'd much rather call a method on the `Factory` class its... | [The Factory class > Convenience methods]
### Convenience methods
As you're well aware by this point, convenience methods are a staple of my coding style. I definitely dislike having to find the appropriate factory to call every time I need to create an object. I'd much rather call a method on the `Factory` class its... | code_snippets | ||
18bac03b-9134-41c0-a3d4-c8b055009ba2 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 2 | SemanticChunker@1.0.0 | 6ff581f03e98ef337b50234a48bbd4ac5d031cbe20eeaf7f8cf05f93d44166fa | [The idea > Setting up the codebase]
## Setting up the codebase
Before we move any further, I think it's wise to set up the directory structure, as well as some conventions for how files are loaded. I'm using [**ESM** (ECMAScript Modules)](https://nodejs.org/api/esm.html) for this project, so I can use `import` and `... | unknown | unknown | [The idea > Setting up the codebase]
## Setting up the codebase
Before we move any further, I think it's wise to set up the directory structure, as well as some conventions for how files are loaded. I'm using [**ESM** (ECMAScript Modules)](https://nodejs.org/api/esm.html) for this project, so I can use `import` and `... | [The idea > Setting up the codebase]
## Setting up the codebase
Before we move any further, I think it's wise to set up the directory structure, as well as some conventions for how files are loaded. I'm using [**ESM** (ECMAScript Modules)](https://nodejs.org/api/esm.html) for this project, so I can use `import` and `... | code_snippets | ||
4854e343-fa8d-41f9-bdc2-2a025feafb27 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 5 | SemanticChunker@1.0.0 | 88dabf181c580e11865841d454e7aa28b9728dc03e009006a18f26f94c2b90fa | [The idea > The core classes]
## The core classes
At the core of this project are two main classes: `Model`, `RecordSet`. In future articles, we'll explore some more of the features that can be added to these classes, but for now, let's focus on the basics.
The `Model` is the **base class** for all models. Its job i... | unknown | unknown | [The idea > The core classes]
## The core classes
At the core of this project are two main classes: `Model`, `RecordSet`. In future articles, we'll explore some more of the features that can be added to these classes, but for now, let's focus on the basics.
The `Model` is the **base class** for all models. Its job i... | [The idea > The core classes]
## The core classes
At the core of this project are two main classes: `Model`, `RecordSet`. In future articles, we'll explore some more of the features that can be added to these classes, but for now, let's focus on the basics.
The `Model` is the **base class** for all models. Its job i... | code_snippets | ||
528d2c72-040c-4b0b-af1f-5505b60cee1a | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 9 | SemanticChunker@1.0.0 | 3310b0a78acf79bd974c589e6030bfd909c6b2a6bdb445efd25b1be2cc79171f | [Record querying > The `where` method]
### The `where` method
The single most useful piece of functionality we need to implement is the `where` method. This method will allow us to **query records based on their attributes**. Again, drawing inspiration from ActiveRecord, I chose to give it a great degree of flexibili... | unknown | unknown | [Record querying > The `where` method]
### The `where` method
The single most useful piece of functionality we need to implement is the `where` method. This method will allow us to **query records based on their attributes**. Again, drawing inspiration from ActiveRecord, I chose to give it a great degree of flexibili... | [Record querying > The `where` method]
### The `where` method
The single most useful piece of functionality we need to implement is the `where` method. This method will allow us to **query records based on their attributes**. Again, drawing inspiration from ActiveRecord, I chose to give it a great degree of flexibili... | code_snippets | ||
5f0665f9-1166-4985-ac9c-d419a750a910 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 8 | SemanticChunker@1.0.0 | 83133473077bb58a270b3a6692fd2052ad381ba652b4b01bcddb83523b6f48b5 | [The idea > Record querying]
## Record querying
Querying records is the most crucial part of this implementation. After all, it's the main reason we're doing this. We can create a `RecordSet` as a **subclass** of `Array` class to handle this responsibility. It provides a way to query records based on their attributes... | unknown | unknown | [The idea > Record querying]
## Record querying
Querying records is the most crucial part of this implementation. After all, it's the main reason we're doing this. We can create a `RecordSet` as a **subclass** of `Array` class to handle this responsibility. It provides a way to query records based on their attributes... | [The idea > Record querying]
## Record querying
Querying records is the most crucial part of this implementation. After all, it's the main reason we're doing this. We can create a `RecordSet` as a **subclass** of `Array` class to handle this responsibility. It provides a way to query records based on their attributes... | code_snippets | ||
6466b4c6-d6b6-4f7a-a0a5-d0c83359c600 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 0 | SemanticChunker@1.0.0 | bdae3efbbaa825bcfd032be059a547b926096972f9c30667ad89663cb34ad39a | ---
title: Modeling complex JavaScript object collections in memory
shortTitle: Complex object collections modeling
language: javascript
tags: [object,class]
cover: digital-nomad-4
excerpt: A deep dive into a fairly flexible implementation, inspired by Rails' ActiveRecord, for modeling JavaScript object collections in ... | unknown | unknown | ---
title: Modeling complex JavaScript object collections in memory
shortTitle: Complex object collections modeling
language: javascript
tags: [object,class]
cover: digital-nomad-4
excerpt: A deep dive into a fairly flexible implementation, inspired by Rails' ActiveRecord, for modeling JavaScript object collections in ... | ---
title: Modeling complex JavaScript object collections in memory
shortTitle: Complex object collections modeling
language: javascript
tags: [object,class]
cover: digital-nomad-4
excerpt: A deep dive into a fairly flexible implementation, inspired by Rails' ActiveRecord, for modeling JavaScript object collections in ... | code_snippets | ||
6626df32-a3d9-4eb6-873d-a32c083f107b | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 17 | SemanticChunker@1.0.0 | 2b6c8c174a7784150214d10c4ae525954f8635db7cbedb1bc939f6e4e92bc52f | [Finishing touches > Partial records]
```js title="src/core/recordSet.js"
export default class RecordSet extends Array {
where(query) {
return RecordSet.from(
this.filter(record => {
return Object.keys(query).every(key => {
// If function use it to determine matches
if (typeof query[key] === 'function')
return ... | unknown | unknown | [Finishing touches > Partial records]
```js title="src/core/recordSet.js"
export default class RecordSet extends Array {
where(query) {
return RecordSet.from(
this.filter(record => {
return Object.keys(query).every(key => {
// If function use it to determine matches
if (typeof query[key] === 'function')
return ... | [Finishing touches > Partial records]
```js title="src/core/recordSet.js"
export default class RecordSet extends Array {
where(query) {
return RecordSet.from(
this.filter(record => {
return Object.keys(query).every(key => {
// If function use it to determine matches
if (typeof query[key] === 'function')
return ... | code_snippets | ||
7c210384-9129-4f2a-82e1-dc073cb7a822 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 16 | SemanticChunker@1.0.0 | ee8f73575769d7f4f6f4f9fe3426b5d77d16629323d0246e18e08edcce28f05f | [Finishing touches > Partial records]
```
If you're asking how are these different from `Array.prototype.map()`, they're merely a convenience wrapper around it. We intentionally return a `RecordSet` from these methods, so we can chain them with other `RecordSet` methods. Remember `RecordSet` instances are also arrays... | unknown | unknown | [Finishing touches > Partial records]
```
If you're asking how are these different from `Array.prototype.map()`, they're merely a convenience wrapper around it. We intentionally return a `RecordSet` from these methods, so we can chain them with other `RecordSet` methods. Remember `RecordSet` instances are also arrays... | [Finishing touches > Partial records]
```
If you're asking how are these different from `Array.prototype.map()`, they're merely a convenience wrapper around it. We intentionally return a `RecordSet` from these methods, so we can chain them with other `RecordSet` methods. Remember `RecordSet` instances are also arrays... | code_snippets | ||
850b6f19-55ad-4c27-b1d7-ed357e4ebf9e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 12 | SemanticChunker@1.0.0 | d995d6b4241619d5bc746ccf8b5369a4650f1b894be772573b61d71dfd0ecbe9 | [Record querying > The `where` method]
```js
const posts = [
new Post({ id: 1, title: 'A post', content: '...' }),
new Post({ id: 2, title: 'Other post', content: '...' }),
new Post({ id: 3, title: 'A draft', content: '...' }),
];
Post.all.where({ title: 'First post' });
// [Post { id: 1, title: 'First post', cont... | unknown | unknown | [Record querying > The `where` method]
```js
const posts = [
new Post({ id: 1, title: 'A post', content: '...' }),
new Post({ id: 2, title: 'Other post', content: '...' }),
new Post({ id: 3, title: 'A draft', content: '...' }),
];
Post.all.where({ title: 'First post' });
// [Post { id: 1, title: 'First post', cont... | [Record querying > The `where` method]
```js
const posts = [
new Post({ id: 1, title: 'A post', content: '...' }),
new Post({ id: 2, title: 'Other post', content: '...' }),
new Post({ id: 3, title: 'A draft', content: '...' }),
];
Post.all.where({ title: 'First post' });
// [Post { id: 1, title: 'First post', cont... | code_snippets | ||
88a078d1-58c5-4fe1-af3f-245fd311f530 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 1 | SemanticChunker@1.0.0 | 429408b1b2aa43a15ee8baf2a5b256b7fdf902f97f9e1ecd95c0577bc49b4b8c | [The idea]
## The idea
What I wanted to accomplish with this project is to have a way to load a fairly large amount of plain objects, which are related to each other. Instead of JavaScript's nesting, referencing and moving around things, I wanted something simple and elegant.
ActiveRecord was my initial inspiration,... | unknown | unknown | [The idea]
## The idea
What I wanted to accomplish with this project is to have a way to load a fairly large amount of plain objects, which are related to each other. Instead of JavaScript's nesting, referencing and moving around things, I wanted something simple and elegant.
ActiveRecord was my initial inspiration,... | [The idea]
## The idea
What I wanted to accomplish with this project is to have a way to load a fairly large amount of plain objects, which are related to each other. Instead of JavaScript's nesting, referencing and moving around things, I wanted something simple and elegant.
ActiveRecord was my initial inspiration,... | code_snippets | ||
9ae0395a-39a3-4c69-a780-1d1c7a485ff5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 13 | SemanticChunker@1.0.0 | 55b6bc515f41c33157f2b74f82a7d16951014c8fd0958b37079a2cc01edb202a | [Record querying > Leveraging array methods]
### Leveraging array methods
Querying is relatively simple using `where`, but we can also use other array methods. For example, we can map over the records or even reduce them!
```js
Post.all.map(post => post.title);
// ['A post', 'Other post', 'A draft']
Post.all.reduce... | unknown | unknown | [Record querying > Leveraging array methods]
### Leveraging array methods
Querying is relatively simple using `where`, but we can also use other array methods. For example, we can map over the records or even reduce them!
```js
Post.all.map(post => post.title);
// ['A post', 'Other post', 'A draft']
Post.all.reduce... | [Record querying > Leveraging array methods]
### Leveraging array methods
Querying is relatively simple using `where`, but we can also use other array methods. For example, we can map over the records or even reduce them!
```js
Post.all.map(post => post.title);
// ['A post', 'Other post', 'A draft']
Post.all.reduce... | code_snippets | ||
9f85af6c-0e11-4b5a-8f8d-9c9617486ebc | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 4 | SemanticChunker@1.0.0 | c5ddc1fda281f47cb8c9a3c8bdc99e832a8f06b5386d8c228511b76f4a70cec9 | [Setting up the codebase > Import aliases]
### Import aliases
I've also set up the `imports` field in `package.json` to **alias** the `src` directory. This way, files can be imported using the `#src` alias, instead of having to use **relative paths**.
```json
// package.json
{
"imports": {
"#src/*": [
"./src/*"
... | unknown | unknown | [Setting up the codebase > Import aliases]
### Import aliases
I've also set up the `imports` field in `package.json` to **alias** the `src` directory. This way, files can be imported using the `#src` alias, instead of having to use **relative paths**.
```json
// package.json
{
"imports": {
"#src/*": [
"./src/*"
... | [Setting up the codebase > Import aliases]
### Import aliases
I've also set up the `imports` field in `package.json` to **alias** the `src` directory. This way, files can be imported using the `#src` alias, instead of having to use **relative paths**.
```json
// package.json
{
"imports": {
"#src/*": [
"./src/*"
... | code_snippets | ||
a097b39c-e6f7-4841-bf3f-9b1f3ef735f6 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 11 | SemanticChunker@1.0.0 | f9ebf241cd3f959f31c361474351aa1fcd0f699378c81da7369e093f288e0df5 | [Record querying > The `where` method]
```
## More record querying
Having set up the two core classes and loaded some data into memory, we should finally be able to query the records. Except, we don't have any way to query them yet.
This is yet another responsibility for the `Model` class. Leveraging the resolution... | unknown | unknown | [Record querying > The `where` method]
```
## More record querying
Having set up the two core classes and loaded some data into memory, we should finally be able to query the records. Except, we don't have any way to query them yet.
This is yet another responsibility for the `Model` class. Leveraging the resolution... | [Record querying > The `where` method]
```
## More record querying
Having set up the two core classes and loaded some data into memory, we should finally be able to query the records. Except, we don't have any way to query them yet.
This is yet another responsibility for the `Model` class. Leveraging the resolution... | code_snippets | ||
a9a7efbb-d789-4d72-9891-70d105782105 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 10 | SemanticChunker@1.0.0 | 61adbea830a58a25501c9727100491159f1dff9d32ba56e5ce51813599405406 | [Record querying > The `where` method]
```
This implementation allows us to query records based on their attributes. It expects a query object, where **each key is an attribute name** and **each value is the expected value**. The expectation can then vary quite a lot, namely:
- Given a **comparator function**, it wi... | unknown | unknown | [Record querying > The `where` method]
```
This implementation allows us to query records based on their attributes. It expects a query object, where **each key is an attribute name** and **each value is the expected value**. The expectation can then vary quite a lot, namely:
- Given a **comparator function**, it wi... | [Record querying > The `where` method]
```
This implementation allows us to query records based on their attributes. It expects a query object, where **each key is an attribute name** and **each value is the expected value**. The expectation can then vary quite a lot, namely:
- Given a **comparator function**, it wi... | code_snippets | ||
b3c8fa0a-b91b-4aeb-abd5-e97290b5f6ac | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 14 | SemanticChunker@1.0.0 | 2227dbe83509a457960223ba43a64ca8c4a72a54a83a115421417f176c02ae13 | [Finishing touches > Querying in the model]
### Querying in the model
First off, I want to make `where` available to the models themselves. Calling `all` seems a little to verbose, after all.
```js title="src/core/model.js"
export default class Model {
// ...
static where(query) {
return this.all.where(query);
}... | unknown | unknown | [Finishing touches > Querying in the model]
### Querying in the model
First off, I want to make `where` available to the models themselves. Calling `all` seems a little to verbose, after all.
```js title="src/core/model.js"
export default class Model {
// ...
static where(query) {
return this.all.where(query);
}... | [Finishing touches > Querying in the model]
### Querying in the model
First off, I want to make `where` available to the models themselves. Calling `all` seems a little to verbose, after all.
```js title="src/core/model.js"
export default class Model {
// ...
static where(query) {
return this.all.where(query);
}... | code_snippets | ||
c5b7e6ff-762f-41b5-b38e-a815529d8c19 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 15 | SemanticChunker@1.0.0 | e769f25bd960b1d9d6a004d1e72d54da5e3e0c817ed1654c487ac91bdfa403c9 | [Finishing touches > Partial records]
### Partial records
Finally, I'd like a way to quickly **pull some attributes** from the records or create a set of **partial records**. This is where we can leverage the array-like behavior of the `RecordSet` and combine it with the power of `Array.prototype.map()`.
A `pluck` m... | unknown | unknown | [Finishing touches > Partial records]
### Partial records
Finally, I'd like a way to quickly **pull some attributes** from the records or create a set of **partial records**. This is where we can leverage the array-like behavior of the `RecordSet` and combine it with the power of `Array.prototype.map()`.
A `pluck` m... | [Finishing touches > Partial records]
### Partial records
Finally, I'd like a way to quickly **pull some attributes** from the records or create a set of **partial records**. This is where we can leverage the array-like behavior of the `RecordSet` and combine it with the power of `Array.prototype.map()`.
A `pluck` m... | code_snippets | ||
e79a3244-286f-4aa5-bdba-bf68eec8b0fd | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 3 | SemanticChunker@1.0.0 | 51df3ad8966102db59e826dfbacdfbeff2c1a104fcef6a9fbaf129aac6ac5209 | [Setting up the codebase > Directory structure]
### Directory structure
The overall directory structure looks like this:
```plaintext
src/
├── core/
│ ├── model.js
│ └── recordSet.js
└── models/
└── post.js
```
We'll come to expand upon this setup in future posts, but for now, this is all we need. The `core` direc... | unknown | unknown | [Setting up the codebase > Directory structure]
### Directory structure
The overall directory structure looks like this:
```plaintext
src/
├── core/
│ ├── model.js
│ └── recordSet.js
└── models/
└── post.js
```
We'll come to expand upon this setup in future posts, but for now, this is all we need. The `core` direc... | [Setting up the codebase > Directory structure]
### Directory structure
The overall directory structure looks like this:
```plaintext
src/
├── core/
│ ├── model.js
│ └── recordSet.js
└── models/
└── post.js
```
We'll come to expand upon this setup in future posts, but for now, this is all we need. The `core` direc... | code_snippets | ||
eb062409-cf06-4169-a8c6-3737affa1982 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 7 | SemanticChunker@1.0.0 | 039f6cd207020928f512a1ad7f65d52c66bb41da387340c06f3c957f532c6fcf | [Models & instances > Preparing the storage]
### Preparing the storage
But how and where will we create such a storage? Well, in the `Model` class, obviously! And, while we're at it, we can create a static method to prepare the storage for each model class. We'll later explore what other useful things we can bundle i... | unknown | unknown | [Models & instances > Preparing the storage]
### Preparing the storage
But how and where will we create such a storage? Well, in the `Model` class, obviously! And, while we're at it, we can create a static method to prepare the storage for each model class. We'll later explore what other useful things we can bundle i... | [Models & instances > Preparing the storage]
### Preparing the storage
But how and where will we create such a storage? Well, in the `Model` class, obviously! And, while we're at it, we can create a static method to prepare the storage for each model class. We'll later explore what other useful things we can bundle i... | code_snippets | ||
fb95f1c6-7c43-40b0-9658-78b43f104e55 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-collections-in-memory.md | unknown | c16297ce-0dad-4099-8317-408761657181 | 6 | SemanticChunker@1.0.0 | bcdda6675bcd1863d8d8e7ac85b0887c08143e242c33942cde6ebeae68e0bd71 | [The idea > Models & instances]
## Models & instances
As we've already mentioned, all model records are **immutable** and loaded into memory. This means that each model's records are known ahead of time, so each model class can have a `static` property to store all of its instances.
Unfortunately, if we are to creat... | unknown | unknown | [The idea > Models & instances]
## Models & instances
As we've already mentioned, all model records are **immutable** and loaded into memory. This means that each model's records are known ahead of time, so each model class can have a `static` property to store all of its instances.
Unfortunately, if we are to creat... | [The idea > Models & instances]
## Models & instances
As we've already mentioned, all model records are **immutable** and loaded into memory. This means that each model's records are known ahead of time, so each model class can have a `static` property to store all of its instances.
Unfortunately, if we are to creat... | code_snippets | ||
12d8ad60-dec3-413a-844d-8cdf20288429 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 13 | SemanticChunker@1.0.0 | 96219d639ecbb3d2e247c3eda2b50e7d7149c666bb65664e74dcadeb6f9a10a6 | [Directory structure > Adding more serializers]
## Adding more serializers
As we've already seen, the serializer itself is not tied to the model. This means we can create another serializer with similar attributes, but different underlying implementations. Let's create a `PostPreviewSerializer` that will serialize a ... | unknown | unknown | [Directory structure > Adding more serializers]
## Adding more serializers
As we've already seen, the serializer itself is not tied to the model. This means we can create another serializer with similar attributes, but different underlying implementations. Let's create a `PostPreviewSerializer` that will serialize a ... | [Directory structure > Adding more serializers]
## Adding more serializers
As we've already seen, the serializer itself is not tied to the model. This means we can create another serializer with similar attributes, but different underlying implementations. Let's create a `PostPreviewSerializer` that will serialize a ... | code_snippets | ||
16560624-1de3-42db-83f7-281cf53f5404 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 11 | SemanticChunker@1.0.0 | f8e37669e11cf77fab211e9dcbc59ca45e1e041929a8cba04319d0869a4f16b8 | [Attribute serialization > Custom attributes]
```
Luckily, this time around, our `serialize` method doesn't need any changes. We can now define a custom attribute in our `PostSerializer`. Let's do that for our `date` attribute, which will format the `publishedAt` attribute into a human-readable date. While we're at i... | unknown | unknown | [Attribute serialization > Custom attributes]
```
Luckily, this time around, our `serialize` method doesn't need any changes. We can now define a custom attribute in our `PostSerializer`. Let's do that for our `date` attribute, which will format the `publishedAt` attribute into a human-readable date. While we're at i... | [Attribute serialization > Custom attributes]
```
Luckily, this time around, our `serialize` method doesn't need any changes. We can now define a custom attribute in our `PostSerializer`. Let's do that for our `date` attribute, which will format the `publishedAt` attribute into a human-readable date. While we're at i... | code_snippets | ||
189cffba-f1b0-4fff-b59a-c835c9366d24 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 8 | SemanticChunker@1.0.0 | 4c307286d9d2ed1686af93e842a1d47a1bc4e21b8c05526e63a0bdcd13561609 | [Attribute serialization > Renaming attributes]
### Renaming attributes
Sometimes, it's necessary to **rename attributes** when serializing them. One could argue that you can simply add more attribute getters to your models and that would work to an extent, but it would make the models unwieldy and harder to maintain... | unknown | unknown | [Attribute serialization > Renaming attributes]
### Renaming attributes
Sometimes, it's necessary to **rename attributes** when serializing them. One could argue that you can simply add more attribute getters to your models and that would work to an extent, but it would make the models unwieldy and harder to maintain... | [Attribute serialization > Renaming attributes]
### Renaming attributes
Sometimes, it's necessary to **rename attributes** when serializing them. One could argue that you can simply add more attribute getters to your models and that would work to an extent, but it would make the models unwieldy and harder to maintain... | code_snippets | ||
1ef461bf-9c4c-4cca-9738-10a65b4ee3c5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 3 | SemanticChunker@1.0.0 | af15460d17373f3a4af593b5b352d1b5e2e231bd119b6e90455e45ecf8cbb1f3 | [Serialization > Flexible serialization]
### Flexible serialization
I'm not exactly sure how common my mileage is in this matter, but I'm quite used to serializers being somewhat **separate from models**. Oftentimes, a serializer will be akin to a view into the model, rather than a one-to-one representation. This is ... | unknown | unknown | [Serialization > Flexible serialization]
### Flexible serialization
I'm not exactly sure how common my mileage is in this matter, but I'm quite used to serializers being somewhat **separate from models**. Oftentimes, a serializer will be akin to a view into the model, rather than a one-to-one representation. This is ... | [Serialization > Flexible serialization]
### Flexible serialization
I'm not exactly sure how common my mileage is in this matter, but I'm quite used to serializers being somewhat **separate from models**. Oftentimes, a serializer will be akin to a view into the model, rather than a one-to-one representation. This is ... | code_snippets | ||
2692a678-56d1-4139-9f55-71bdc517f452 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 4 | SemanticChunker@1.0.0 | 59f7711433d3c3299591008735a872f6619cbd67575ea713cfc385e5e2d20c78 | [Serialization > Flexible serialization]
```js
const author = new Author({
id: 1,
name: 'John',
surname: 'Doe',
email: 'j.doe@authornet.io'
});
const post = new Post({
id: 1,
title: 'Hello, World!',
content: 'Lorem ipsum dolor sit amet.',
publishedAt: new Date('2024-12-01') ,
authorId: 1
});
// Sample of a ... | unknown | unknown | [Serialization > Flexible serialization]
```js
const author = new Author({
id: 1,
name: 'John',
surname: 'Doe',
email: 'j.doe@authornet.io'
});
const post = new Post({
id: 1,
title: 'Hello, World!',
content: 'Lorem ipsum dolor sit amet.',
publishedAt: new Date('2024-12-01') ,
authorId: 1
});
// Sample of a ... | [Serialization > Flexible serialization]
```js
const author = new Author({
id: 1,
name: 'John',
surname: 'Doe',
email: 'j.doe@authornet.io'
});
const post = new Post({
id: 1,
title: 'Hello, World!',
content: 'Lorem ipsum dolor sit amet.',
publishedAt: new Date('2024-12-01') ,
authorId: 1
});
// Sample of a ... | code_snippets | ||
446f5899-b48e-41f6-9efc-3ddd4186b950 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 17 | SemanticChunker@1.0.0 | 0ec69b0d23e1b25bb7ffca3b0d83d77d90c1a996f632fadbd04a6964bde229bd | [Directory structure > Convenience methods]
```
```js title="src/core/serializer.js"
export default class Serializer {
static prepare(serializer, serializableAttributes) {
serializer.serializableAttributes = [];
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const attr... | unknown | unknown | [Directory structure > Convenience methods]
```
```js title="src/core/serializer.js"
export default class Serializer {
static prepare(serializer, serializableAttributes) {
serializer.serializableAttributes = [];
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const attr... | [Directory structure > Convenience methods]
```
```js title="src/core/serializer.js"
export default class Serializer {
static prepare(serializer, serializableAttributes) {
serializer.serializableAttributes = [];
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const attr... | code_snippets | ||
51537f5f-910c-4c05-930a-7169984dab58 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 9 | SemanticChunker@1.0.0 | 775498b583f2aadf0126be4fc9b88d619899de698fa3c15c41164d35ed7ba73c | [Attribute serialization > Renaming attributes]
```
There are a few things to unpack here. The `prepare` method can accept a **mix of strings and arrays**. If an array is detected, the first element is used as the serialized attribute name, while the second element is used as the attribute getter name. If no second e... | unknown | unknown | [Attribute serialization > Renaming attributes]
```
There are a few things to unpack here. The `prepare` method can accept a **mix of strings and arrays**. If an array is detected, the first element is used as the serialized attribute name, while the second element is used as the attribute getter name. If no second e... | [Attribute serialization > Renaming attributes]
```
There are a few things to unpack here. The `prepare` method can accept a **mix of strings and arrays**. If an array is detected, the first element is used as the serialized attribute name, while the second element is used as the attribute getter name. If no second e... | code_snippets | ||
6d68e77f-b8af-4e02-af4e-97ba0a562792 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 18 | SemanticChunker@1.0.0 | 331a0e8abd789e7ca2fb93e8974c7a6bbe66599081a2a6deeec05a8c811fa176 | [Directory structure > Convenience methods]
static byNew(records) {
return records.order((a, b) => b.publishedAt - a.publishedAt);
}
get isPublished() {
return this.publishedAt <= new Date();
}
get author() {
return Author.find(this.authorId);
}
}
```
```js title="src/models/author.js"
import Model from '#... | unknown | unknown | [Directory structure > Convenience methods]
static byNew(records) {
return records.order((a, b) => b.publishedAt - a.publishedAt);
}
get isPublished() {
return this.publishedAt <= new Date();
}
get author() {
return Author.find(this.authorId);
}
}
```
```js title="src/models/author.js"
import Model from '#... | [Directory structure > Convenience methods]
static byNew(records) {
return records.order((a, b) => b.publishedAt - a.publishedAt);
}
get isPublished() {
return this.publishedAt <= new Date();
}
get author() {
return Author.find(this.authorId);
}
}
```
```js title="src/models/author.js"
import Model from '#... | code_snippets | ||
6dbc173b-a0bc-4055-a66a-298949c6df7d | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 12 | SemanticChunker@1.0.0 | 0dbefbfdc32e43c16cf37a27b894829a98953a545cd006bc7d00bdbe6673a4ab | [Attribute serialization > Custom attributes]
export default class PostSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['content', post => `<p>${post.content}</p>`],
['date', post => {
const date = new Date(post.publishedAt);
return date.toLocaleDateString('en-US', {
weekday: 'short',
... | unknown | unknown | [Attribute serialization > Custom attributes]
export default class PostSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['content', post => `<p>${post.content}</p>`],
['date', post => {
const date = new Date(post.publishedAt);
return date.toLocaleDateString('en-US', {
weekday: 'short',
... | [Attribute serialization > Custom attributes]
export default class PostSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['content', post => `<p>${post.content}</p>`],
['date', post => {
const date = new Date(post.publishedAt);
return date.toLocaleDateString('en-US', {
weekday: 'short',
... | code_snippets | ||
738b7b5f-7537-4486-8fe1-6346df73a16f | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 6 | SemanticChunker@1.0.0 | a28f5f59fdb9e7adaa0e402fb4cc366c434b1553e5703d38817cf8de8dedb4f8 | [Attribute serialization > Serializing attributes]
### Serializing attributes
To create our `Serializer` class, we'll start by defining a simple `constructor`. It will accept a `subject` to serialize and an `options` object. Via the options object, we can pass additional configuration, which can be used later down th... | unknown | unknown | [Attribute serialization > Serializing attributes]
### Serializing attributes
To create our `Serializer` class, we'll start by defining a simple `constructor`. It will accept a `subject` to serialize and an `options` object. Via the options object, we can pass additional configuration, which can be used later down th... | [Attribute serialization > Serializing attributes]
### Serializing attributes
To create our `Serializer` class, we'll start by defining a simple `constructor`. It will accept a `subject` to serialize and an `options` object. Via the options object, we can pass additional configuration, which can be used later down th... | code_snippets | ||
8748d94d-5d81-4e2a-98cb-8a9abba8b9e8 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 16 | SemanticChunker@1.0.0 | 2fbd4cca7752c88d4b293daa4b59ac65147327b02fe09aece1d1f9f89ad47129 | [Directory structure > Convenience methods]
```
# [continued: part 1]
static where(query) {
return this.all.where(query);
}
static order(comparator) {
return this.all.order(comparator);
}
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
retu... | unknown | unknown | [Directory structure > Convenience methods]
```
# [continued: part 1]
static where(query) {
return this.all.where(query);
}
static order(comparator) {
return this.all.order(comparator);
}
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
retu... | [Directory structure > Convenience methods]
```
# [continued: part 1]
static where(query) {
return this.all.where(query);
}
static order(comparator) {
return this.all.order(comparator);
}
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
retu... | code_snippets | ||
952ec2b4-09ba-4a58-b6c7-0ee7707fb5ff | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 0 | SemanticChunker@1.0.0 | e45c8ba84859dca3d9babf14e96bc7da4ef68a390fce38a7580b63c5606ea8cc | ---
title: Modeling complex JavaScript object serialization
shortTitle: Complex object serialization
language: javascript
tags: [object,class]
cover: coffee-phone-tray
excerpt: In the fourth part of the series, we will look at how to serialize complex JavaScript objects.
listed: true
dateModified: 2024-12-26
journeyId:... | unknown | unknown | ---
title: Modeling complex JavaScript object serialization
shortTitle: Complex object serialization
language: javascript
tags: [object,class]
cover: coffee-phone-tray
excerpt: In the fourth part of the series, we will look at how to serialize complex JavaScript objects.
listed: true
dateModified: 2024-12-26
journeyId:... | ---
title: Modeling complex JavaScript object serialization
shortTitle: Complex object serialization
language: javascript
tags: [object,class]
cover: coffee-phone-tray
excerpt: In the fourth part of the series, we will look at how to serialize complex JavaScript objects.
listed: true
dateModified: 2024-12-26
journeyId:... | code_snippets | ||
962e04a7-43ab-4e0d-9f93-cfecd5d7c77e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 14 | SemanticChunker@1.0.0 | d16cd4b8239cba13b90d4a5def6bddd8887085c9ba97b760b08318c11d1b8d9b | [Directory structure > Convenience methods]
## Convenience methods
You're probably used to it by now, but I really love me some **convenience methods**. This time around, we'll keep it simple, adding two static methods to the `Serializer` class, `serialize` and `serializeArray`. The former will create a new instance ... | unknown | unknown | [Directory structure > Convenience methods]
## Convenience methods
You're probably used to it by now, but I really love me some **convenience methods**. This time around, we'll keep it simple, adding two static methods to the `Serializer` class, `serialize` and `serializeArray`. The former will create a new instance ... | [Directory structure > Convenience methods]
## Convenience methods
You're probably used to it by now, but I really love me some **convenience methods**. This time around, we'll keep it simple, adding two static methods to the `Serializer` class, `serialize` and `serializeArray`. The former will create a new instance ... | code_snippets | ||
b0f526a8-88b7-4ef6-bc0a-9dc8c2d58f00 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 5 | SemanticChunker@1.0.0 | e244d02bdc80a7d9104ac31f2ae62858288548921b659ae0a7d805a63a8a9ee4 | [Directory structure > Attribute serialization]
## Attribute serialization
Each model has its own **attributes**, which, if you remember, are [getter functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get). As these attributes are easily accessible and often cached in memory, we ca... | unknown | unknown | [Directory structure > Attribute serialization]
## Attribute serialization
Each model has its own **attributes**, which, if you remember, are [getter functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get). As these attributes are easily accessible and often cached in memory, we ca... | [Directory structure > Attribute serialization]
## Attribute serialization
Each model has its own **attributes**, which, if you remember, are [getter functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get). As these attributes are easily accessible and often cached in memory, we ca... | code_snippets | ||
c1831938-7ff6-43a6-9934-20dd44cf2cb5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 7 | SemanticChunker@1.0.0 | 4aefa1c794e9f48faaf84dfa22ee66b8e40751f62bf82d37689f1fbd2052ae5f | [Attribute serialization > Serializing attributes]
```
> [!NOTE]
>
> In this post, I **won't be covering the conversion to a JSON string**, as it's a trivial task, using `JSON.stringify()`. Instead, I'll focus on the **structure** of the serialized object.
Notice the use of `this.constructor` instead of `Serializer`... | unknown | unknown | [Attribute serialization > Serializing attributes]
```
> [!NOTE]
>
> In this post, I **won't be covering the conversion to a JSON string**, as it's a trivial task, using `JSON.stringify()`. Instead, I'll focus on the **structure** of the serialized object.
Notice the use of `this.constructor` instead of `Serializer`... | [Attribute serialization > Serializing attributes]
```
> [!NOTE]
>
> In this post, I **won't be covering the conversion to a JSON string**, as it's a trivial task, using `JSON.stringify()`. Instead, I'll focus on the **structure** of the serialized object.
Notice the use of `this.constructor` instead of `Serializer`... | code_snippets | ||
e33d971c-aec2-42e2-933c-409c64103b42 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 10 | SemanticChunker@1.0.0 | d53756060b330253e267162df990a2ebf5153fe40a91ff3f147d058dea71bbb3 | [Attribute serialization > Custom attributes]
### Custom attributes
Expanding upon the alias system, one could easily imagine a scenario where you'd want to serialize an **attribute that doesn't exist on the model**. This could be a calculated attribute, a combination of other attributes, or even a completely unrelat... | unknown | unknown | [Attribute serialization > Custom attributes]
### Custom attributes
Expanding upon the alias system, one could easily imagine a scenario where you'd want to serialize an **attribute that doesn't exist on the model**. This could be a calculated attribute, a combination of other attributes, or even a completely unrelat... | [Attribute serialization > Custom attributes]
### Custom attributes
Expanding upon the alias system, one could easily imagine a scenario where you'd want to serialize an **attribute that doesn't exist on the model**. This could be a calculated attribute, a combination of other attributes, or even a completely unrelat... | code_snippets | ||
e9115acf-4ef5-4e74-81dc-c2269ee8bfed | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 19 | SemanticChunker@1.0.0 | d372638ab62026f70dc75e9b186da9e5c714c5939e54e633d2549adf9d3c7962 | [Directory structure > Convenience methods]
```
```js title="src/serializers/postPreviewSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostPreviewSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['date', post => {
const date = new Date(post.published... | unknown | unknown | [Directory structure > Convenience methods]
```
```js title="src/serializers/postPreviewSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostPreviewSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['date', post => {
const date = new Date(post.published... | [Directory structure > Convenience methods]
```
```js title="src/serializers/postPreviewSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostPreviewSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['date', post => {
const date = new Date(post.published... | code_snippets | ||
ea286bac-2b81-4343-a1de-105445c29e64 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 2 | SemanticChunker@1.0.0 | 76c8efc51d17040718e58c23a78f951eb5db117d19229ec1e0320759f6f872c8 | [Directory structure > Serialization]
## Serialization
If you're not familiar, **serialization** is the conversion of an object into a format that can be stored or transmitted. In our case, we want to convert our `Post` and `Author` objects into a format that can be sent to the client. This format is usually **JSON**... | unknown | unknown | [Directory structure > Serialization]
## Serialization
If you're not familiar, **serialization** is the conversion of an object into a format that can be stored or transmitted. In our case, we want to convert our `Post` and `Author` objects into a format that can be sent to the client. This format is usually **JSON**... | [Directory structure > Serialization]
## Serialization
If you're not familiar, **serialization** is the conversion of an object into a format that can be stored or transmitted. In our case, we want to convert our `Post` and `Author` objects into a format that can be sent to the client. This format is usually **JSON**... | code_snippets | ||
fb72d205-47cc-418d-a168-50dc2942a741 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 1 | SemanticChunker@1.0.0 | 9e54307c2c909b993dff15cf4209b51c39364a860d085111d191f59b605f40e5 | [Directory structure]
## Directory structure
As usual, before diving into the code, let's check the directory structure of our project. This time around, we're adding a **new class**, `Serializer`, as well as a **new directory**, called `serializers`.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ └... | unknown | unknown | [Directory structure]
## Directory structure
As usual, before diving into the code, let's check the directory structure of our project. This time around, we're adding a **new class**, `Serializer`, as well as a **new directory**, called `serializers`.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ └... | [Directory structure]
## Directory structure
As usual, before diving into the code, let's check the directory structure of our project. This time around, we're adding a **new class**, `Serializer`, as well as a **new directory**, called `serializers`.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ └... | code_snippets | ||
fe34d0d5-b07d-4bb5-86f0-7538b057a4ef | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-serialization.md | unknown | d744b0ee-4301-473c-af40-1ef9b559fb39 | 15 | SemanticChunker@1.0.0 | 8851f8415c51021950336327b33546c71c3a978a1c1cf1c509c2df12ff0b6ec1 | [Directory structure > Convenience methods]
```
I don't suppose it's necessary to show you how to use these methods, as they're pretty straightforward. All they do is provide us with some **syntactic sugar**, so we don't have to create a new instance of the serializer every time we want to serialize something.
## Co... | unknown | unknown | [Directory structure > Convenience methods]
```
I don't suppose it's necessary to show you how to use these methods, as they're pretty straightforward. All they do is provide us with some **syntactic sugar**, so we don't have to create a new instance of the serializer every time we want to serialize something.
## Co... | [Directory structure > Convenience methods]
```
I don't suppose it's necessary to show you how to use these methods, as they're pretty straightforward. All they do is provide us with some **syntactic sugar**, so we don't have to create a new instance of the serializer every time we want to serialize something.
## Co... | code_snippets | ||
041c367a-5479-4fea-ac61-30945150d220 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 21 | SemanticChunker@1.0.0 | fdf98e725ab3ff6d421b1714f7d89e620605fd400390f44c70c12a1fd3640ead | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
Before I leave you, here's the entire implementation of this series. You can use this as a reference or as a starting point for your own projects. Enjoy!
You can also [browse through the Code Reference on GitHub](https://github.com/Chalarangelo... | unknown | unknown | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
Before I leave you, here's the entire implementation of this series. You can use this as a reference or as a starting point for your own projects. Enjoy!
You can also [browse through the Code Reference on GitHub](https://github.com/Chalarangelo... | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
Before I leave you, here's the entire implementation of this series. You can use this as a reference or as a starting point for your own projects. Enjoy!
You can also [browse through the Code Reference on GitHub](https://github.com/Chalarangelo... | code_snippets | ||
0acfa9c3-282a-4d71-9b7d-5629b391f42e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 2 | SemanticChunker@1.0.0 | dd839f6865edb9ce160a428d676a458713cb0d4a94f8a957b39c418f1f86d015 | [Directory structure > Housekeeping]
## Housekeeping
Before we begin, I want to address a couple of things to make the rest of the implementation easier. Firstly, some cleaning up in the `Model` class's `prepare` method. Then, we'll add our new `Category` model and factory, and finally, we'll add a relationships to o... | unknown | unknown | [Directory structure > Housekeeping]
## Housekeeping
Before we begin, I want to address a couple of things to make the rest of the implementation easier. Firstly, some cleaning up in the `Model` class's `prepare` method. Then, we'll add our new `Category` model and factory, and finally, we'll add a relationships to o... | [Directory structure > Housekeeping]
## Housekeeping
Before we begin, I want to address a couple of things to make the rest of the implementation easier. Firstly, some cleaning up in the `Model` class's `prepare` method. Then, we'll add our new `Category` model and factory, and finally, we'll add a relationships to o... | code_snippets | ||
24144fba-3341-4383-a12c-a2ee9cd82c01 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 9 | SemanticChunker@1.0.0 | 5f042a3fea45646daac6804de080e76f1c151564392055e5a9082ab41f9c5084 | [Relationship definitions > Belongs to]
```
As you can see, we've added a new `models` static variable to the `Model` class. This serves as a **storage for all initialized models**. We then ensure that relationships are stored as **field definitions** in `relationshipFields`, which will then be used to create the ind... | unknown | unknown | [Relationship definitions > Belongs to]
```
As you can see, we've added a new `models` static variable to the `Model` class. This serves as a **storage for all initialized models**. We then ensure that relationships are stored as **field definitions** in `relationshipFields`, which will then be used to create the ind... | [Relationship definitions > Belongs to]
```
As you can see, we've added a new `models` static variable to the `Model` class. This serves as a **storage for all initialized models**. We then ensure that relationships are stored as **field definitions** in `relationshipFields`, which will then be used to create the ind... | code_snippets | ||
2783953a-d1b0-4487-89da-ed3d394df13a | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 11 | SemanticChunker@1.0.0 | eecf7bc230a2fdbabff4e4cfff93609e9dfd81ee911644be682bd29c4443822a | [Relationship definitions > Has one]
```
As you can see, very little has changed from the previous setup. Instead of using the `find` method on the other model, we use `where` with a **query** that utilizes the `foreignKey` to find the related record. This is a very simple implementation, but it should be enough for ... | unknown | unknown | [Relationship definitions > Has one]
```
As you can see, very little has changed from the previous setup. Instead of using the `find` method on the other model, we use `where` with a **query** that utilizes the `foreignKey` to find the related record. This is a very simple implementation, but it should be enough for ... | [Relationship definitions > Has one]
```
As you can see, very little has changed from the previous setup. Instead of using the `find` method on the other model, we use `where` with a **query** that utilizes the `foreignKey` to find the related record. This is a very simple implementation, but it should be enough for ... | code_snippets | ||
2a2ca6a8-3dad-4944-86a0-6800a20b57a1 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 29 | SemanticChunker@1.0.0 | 39425d7aded530d6c7571f98ce6c8bc50c28a8e2f76074240398d79693ff7a4e | [Directory structure > Addendum: Code summary]
```
```js title="src/models/post.js"
import Model from '#src/core/model.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this, {
fields: [
['title', { type: 'string', allowEmpty: false }],
['content', 'str... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/models/post.js"
import Model from '#src/core/model.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this, {
fields: [
['title', { type: 'string', allowEmpty: false }],
['content', 'str... | [Directory structure > Addendum: Code summary]
```
```js title="src/models/post.js"
import Model from '#src/core/model.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this, {
fields: [
['title', { type: 'string', allowEmpty: false }],
['content', 'str... | code_snippets | ||
2f3fd7dc-cb2a-4c73-90cc-49995490e438 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 13 | SemanticChunker@1.0.0 | 01f1a273267f4cca5c3d2ea91e221de3e2301d716a82b2870d83414b1b5e9fd3 | [Relationship definitions > Has one]
> [!NOTE]
>
> Same as last time, I haven't implemented **many-to-many relationships** to minimize complexity. They're left as a task for the reader, if you want to get your hands dirty and you feel like you truly need them for your use case. | unknown | unknown | [Relationship definitions > Has one]
> [!NOTE]
>
> Same as last time, I haven't implemented **many-to-many relationships** to minimize complexity. They're left as a task for the reader, if you want to get your hands dirty and you feel like you truly need them for your use case. | [Relationship definitions > Has one]
> [!NOTE]
>
> Same as last time, I haven't implemented **many-to-many relationships** to minimize complexity. They're left as a task for the reader, if you want to get your hands dirty and you feel like you truly need them for your use case. | code_snippets | ||
39203a34-f4ad-446c-86fb-b5abb7f27936 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 0 | SemanticChunker@1.0.0 | 74953952ead6643008e334702495a3ec83f3edf2712de495205dc21f8ecf1b5a | ---
title: Modeling complex JavaScript object advanced relationships
shortTitle: Complex object advanced relationships
language: javascript
tags: [object,class]
cover: digital-nomad
excerpt: In this installment of the ActiveRecord-like JavaScript implementation, we will revisit modeling relationships between objects.
l... | unknown | unknown | ---
title: Modeling complex JavaScript object advanced relationships
shortTitle: Complex object advanced relationships
language: javascript
tags: [object,class]
cover: digital-nomad
excerpt: In this installment of the ActiveRecord-like JavaScript implementation, we will revisit modeling relationships between objects.
l... | ---
title: Modeling complex JavaScript object advanced relationships
shortTitle: Complex object advanced relationships
language: javascript
tags: [object,class]
cover: digital-nomad
excerpt: In this installment of the ActiveRecord-like JavaScript implementation, we will revisit modeling relationships between objects.
l... | code_snippets | ||
41ac9e13-8eed-4ead-aaba-6366f3ad646b | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 30 | SemanticChunker@1.0.0 | 322d7fd414fd09abcfadbf77d75e8b69db328bde76fc2ba813cf372da49387a0 | [Directory structure > Addendum: Code summary]
```
```js title="src/models/category.js"
import Model from '#src/core/model.js';
export default class Category extends Model {
static {
// Prepare storage for the Category model
super.prepare(this, {
fields: [['title', { type: 'string', allowEmpty: false }]],
relat... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/models/category.js"
import Model from '#src/core/model.js';
export default class Category extends Model {
static {
// Prepare storage for the Category model
super.prepare(this, {
fields: [['title', { type: 'string', allowEmpty: false }]],
relat... | [Directory structure > Addendum: Code summary]
```
```js title="src/models/category.js"
import Model from '#src/core/model.js';
export default class Category extends Model {
static {
// Prepare storage for the Category model
super.prepare(this, {
fields: [['title', { type: 'string', allowEmpty: false }]],
relat... | code_snippets | ||
42c1c695-e955-4a4a-99f7-61ec387894af | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 27 | SemanticChunker@1.0.0 | a6b87ae067460c0f82ba5f7dfdedf3b7ea11adbe832034a80412d9cfe09088cb | [Directory structure > Addendum: Code summary]
export default class Factory {
static factoryMap = new Map();
static modelMap = new Map();
static prepare(factory, model, base = {}, traits = {}) {
const modelName = model.name;
const factoryBase = {};
Object.keys(base).forEach(key => {
const value = base[key];
... | unknown | unknown | [Directory structure > Addendum: Code summary]
export default class Factory {
static factoryMap = new Map();
static modelMap = new Map();
static prepare(factory, model, base = {}, traits = {}) {
const modelName = model.name;
const factoryBase = {};
Object.keys(base).forEach(key => {
const value = base[key];
... | [Directory structure > Addendum: Code summary]
export default class Factory {
static factoryMap = new Map();
static modelMap = new Map();
static prepare(factory, model, base = {}, traits = {}) {
const modelName = model.name;
const factoryBase = {};
Object.keys(base).forEach(key => {
const value = base[key];
... | code_snippets | ||
4496df00-fb92-4915-a3ff-30dc2c39ddb5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 7 | SemanticChunker@1.0.0 | cca8d80d9504791006955abe0aa06f7c0a69531906caa854d796ff28114572e0 | [Relationship definitions > Belongs to]
### Belongs to
Again, drawing inspiration from ActiveRecord, we'll start with the `belongsTo` relationship. This relationship is used when a record belongs to another record. In this case, the record that _belongs to_ the other record is the one defining the **foreign key**.
I... | unknown | unknown | [Relationship definitions > Belongs to]
### Belongs to
Again, drawing inspiration from ActiveRecord, we'll start with the `belongsTo` relationship. This relationship is used when a record belongs to another record. In this case, the record that _belongs to_ the other record is the one defining the **foreign key**.
I... | [Relationship definitions > Belongs to]
### Belongs to
Again, drawing inspiration from ActiveRecord, we'll start with the `belongsTo` relationship. This relationship is used when a record belongs to another record. In this case, the record that _belongs to_ the other record is the one defining the **foreign key**.
I... | code_snippets | ||
489e9d43-721f-4e8d-aa14-e22c0c554a72 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 22 | SemanticChunker@1.0.0 | 28b9183f95f6bf6be4b49f6fa883682e91a63e16e19385d4d87254aa92a78400 | [Directory structure > Addendum: Code summary]
```
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
import util from 'util';
util.inspect.styles.record = 'blue';
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
const capitalize = str => str.charAt(0).toUpperCase(... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
import util from 'util';
util.inspect.styles.record = 'blue';
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
const capitalize = str => str.charAt(0).toUpperCase(... | [Directory structure > Addendum: Code summary]
```
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
import util from 'util';
util.inspect.styles.record = 'blue';
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
const capitalize = str => str.charAt(0).toUpperCase(... | code_snippets | ||
66b74a7e-f383-4d08-8958-f5702762dcbf | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 19 | SemanticChunker@1.0.0 | 0ce1c3d2c6d1cf2668efbbfc93b87df8a10c47df9ea80260489ecce08335dedd | [Relationship customization > Self-referential relationships]
### Self-referential relationships
What we did with the `parent` relationship is what one would call a **self-referential relationship**. This is a relationship where a record can be related to another record of the **same model**. This concept can come in... | unknown | unknown | [Relationship customization > Self-referential relationships]
### Self-referential relationships
What we did with the `parent` relationship is what one would call a **self-referential relationship**. This is a relationship where a record can be related to another record of the **same model**. This concept can come in... | [Relationship customization > Self-referential relationships]
### Self-referential relationships
What we did with the `parent` relationship is what one would call a **self-referential relationship**. This is a relationship where a record can be related to another record of the **same model**. This concept can come in... | code_snippets | ||
87f4d29a-e710-4c3f-99b4-c8497ec5bddb | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 1 | SemanticChunker@1.0.0 | 613dca72ffdb4e06c8ad6a01361f6d16d7822a847781886963e9f441a6bd80c9 | [Directory structure]
## Directory structure
This time, we'll simply add a **new model** under our `models` directory. We'll also implement the relevant **factory** for it to match the rest of the implementation. And we'll make a few updates in the `Model` class and our models to support the new features.
```plainte... | unknown | unknown | [Directory structure]
## Directory structure
This time, we'll simply add a **new model** under our `models` directory. We'll also implement the relevant **factory** for it to match the rest of the implementation. And we'll make a few updates in the `Model` class and our models to support the new features.
```plainte... | [Directory structure]
## Directory structure
This time, we'll simply add a **new model** under our `models` directory. We'll also implement the relevant **factory** for it to match the rest of the implementation. And we'll make a few updates in the `Model` class and our models to support the new features.
```plainte... | code_snippets | ||
97c111c8-8d92-4fa4-9638-89fdeb7c79c1 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 24 | SemanticChunker@1.0.0 | 7a88066b166d0c123cba135ddb428ef0acb5f98115fa441fa48b693b2dd8ec4d | [Directory structure > Addendum: Code summary]
```
# [continued: part 2]
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = model.indexes.reduce((acc, index) => {
acc[index] = new Map();
return acc;
}, {});
}
Object.entries(Object.getOwnPropertyDescriptors... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
# [continued: part 2]
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = model.indexes.reduce((acc, index) => {
acc[index] = new Map();
return acc;
}, {});
}
Object.entries(Object.getOwnPropertyDescriptors... | [Directory structure > Addendum: Code summary]
```
# [continued: part 2]
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = model.indexes.reduce((acc, index) => {
acc[index] = new Map();
return acc;
}, {});
}
Object.entries(Object.getOwnPropertyDescriptors... | code_snippets | ||
9a019427-a4fd-4766-bdd9-1e0013ae3276 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 26 | SemanticChunker@1.0.0 | a5fa76d23b73dab24cf7bb2a1bd568e92d571b1425c9028852d7f7d43c956745 | [Directory structure > Addendum: Code summary]
select(...attributes) {
return RecordSet.from(super.map(record =>
attributes.reduce((acc, attribute) => {
acc[attribute] = record[attribute];
return acc;
}, {})
));
}
get first() {
return this[0];
}
get last() {
return this[this.length - 1];
}
}
```
```js... | unknown | unknown | [Directory structure > Addendum: Code summary]
select(...attributes) {
return RecordSet.from(super.map(record =>
attributes.reduce((acc, attribute) => {
acc[attribute] = record[attribute];
return acc;
}, {})
));
}
get first() {
return this[0];
}
get last() {
return this[this.length - 1];
}
}
```
```js... | [Directory structure > Addendum: Code summary]
select(...attributes) {
return RecordSet.from(super.map(record =>
attributes.reduce((acc, attribute) => {
acc[attribute] = record[attribute];
return acc;
}, {})
));
}
get first() {
return this[0];
}
get last() {
return this[this.length - 1];
}
}
```
```js... | code_snippets | ||
9e581f96-3f56-4185-92c4-04292681845d | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 15 | SemanticChunker@1.0.0 | 21f7b4660ef161ffa6d5389b66a6f1611c77d226d239f5dadaf7f448b99d6edc | [Relationship customization > Foreign keys]
### Foreign keys
Up until this point, **foreign keys** have been dictated by the target model's name. This is a good **default**, but it's not always going to work. We may want to go down the field definition route and allow our second array element to be an **object**. If ... | unknown | unknown | [Relationship customization > Foreign keys]
### Foreign keys
Up until this point, **foreign keys** have been dictated by the target model's name. This is a good **default**, but it's not always going to work. We may want to go down the field definition route and allow our second array element to be an **object**. If ... | [Relationship customization > Foreign keys]
### Foreign keys
Up until this point, **foreign keys** have been dictated by the target model's name. This is a good **default**, but it's not always going to work. We may want to go down the field definition route and allow our second array element to be an **object**. If ... | code_snippets | ||
aa56b985-253e-4bcd-ab1d-0092b3a82009 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 3 | SemanticChunker@1.0.0 | 5615ad445b3cc9016b3193e58d7d6904d73e6856b5fbb92b137a7fe590e26013 | [Housekeeping > Refactoring `prepare`]
### Refactoring `prepare`
In the past, we've heavily relied on the `prepare` method of the `Model` class to set up our models. As we're going to add even more logic to it, the arguments will start becoming a little hard to manage. Let's **switch from a list of arguments to an ob... | unknown | unknown | [Housekeeping > Refactoring `prepare`]
### Refactoring `prepare`
In the past, we've heavily relied on the `prepare` method of the `Model` class to set up our models. As we're going to add even more logic to it, the arguments will start becoming a little hard to manage. Let's **switch from a list of arguments to an ob... | [Housekeeping > Refactoring `prepare`]
### Refactoring `prepare`
In the past, we've heavily relied on the `prepare` method of the `Model` class to set up our models. As we're going to add even more logic to it, the arguments will start becoming a little hard to manage. Let's **switch from a list of arguments to an ob... | code_snippets | ||
acad2878-e253-406b-a38c-2ef1430fe672 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 23 | SemanticChunker@1.0.0 | 64249d3e5b747b471fd476dbb7d05e544755451e06410756f4de5111f772bb20 | [Directory structure > Addendum: Code summary]
```
# [continued: part 1]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
# [continued: part 1]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new... | [Directory structure > Addendum: Code summary]
```
# [continued: part 1]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new... | code_snippets | ||
af1331ad-da50-405f-b3db-f979b2b1d244 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 16 | SemanticChunker@1.0.0 | 78e03772b75dd170df05beac92c578d6a95cd9f440b627b74e09e04db3371bfd | [Relationship customization > Foreign keys]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship ty... | unknown | unknown | [Relationship customization > Foreign keys]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship ty... | [Relationship customization > Foreign keys]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship ty... | code_snippets | ||
b0033fbd-c343-497f-9801-3e8ce0085e5e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 12 | SemanticChunker@1.0.0 | 0169568fa1e5bb40382c97932d6f6f5a310e6d51064a9646ce64124262663211 | [Relationship definitions > Has one]
Ok, apart from that little detail, you may have noticed that we also **ensure the model name is singular**. This is on purpose, so we can declare the relationship in a more human-readable way. For example, in the `Author` model, we can declare a `hasMany` relationship to `Post` as ... | unknown | unknown | [Relationship definitions > Has one]
Ok, apart from that little detail, you may have noticed that we also **ensure the model name is singular**. This is on purpose, so we can declare the relationship in a more human-readable way. For example, in the `Author` model, we can declare a `hasMany` relationship to `Post` as ... | [Relationship definitions > Has one]
Ok, apart from that little detail, you may have noticed that we also **ensure the model name is singular**. This is on purpose, so we can declare the relationship in a more human-readable way. For example, in the `Author` model, we can declare a `hasMany` relationship to `Post` as ... | code_snippets | ||
b8e3e1e6-2ef9-4e42-85b7-9b6a618e6382 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 25 | SemanticChunker@1.0.0 | 7408d77512ddd7910799151cbbf2287f7c3c6926a4d3af0da1ef1dcb452cfea1 | [Directory structure > Addendum: Code summary]
```
# [continued: part 3]
static find(id) {
return Model.indexedInstances[this.name].id.get(id);
}
static findBy(fieldAndValue) {
const entries = Object.entries(fieldAndValue);
if (entries.length !== 1)
throw new Error('findBy method must receive a single field/v... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
# [continued: part 3]
static find(id) {
return Model.indexedInstances[this.name].id.get(id);
}
static findBy(fieldAndValue) {
const entries = Object.entries(fieldAndValue);
if (entries.length !== 1)
throw new Error('findBy method must receive a single field/v... | [Directory structure > Addendum: Code summary]
```
# [continued: part 3]
static find(id) {
return Model.indexedInstances[this.name].id.get(id);
}
static findBy(fieldAndValue) {
const entries = Object.entries(fieldAndValue);
if (entries.length !== 1)
throw new Error('findBy method must receive a single field/v... | code_snippets | ||
b9fd171e-9a88-471c-bc2f-d1b451831629 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 4 | SemanticChunker@1.0.0 | 271f7cf15d44d8ba8c66759a427f45a33318eaa810cc1cc5754175ea40522cc2 | [Housekeeping > Refactoring `prepare`]
```
### Adding the `Category` model
We'll now create a `Category` model and a relevant `CategoryFactory` to match the rest of the implementation. We'll use this model as the main example for some of our relationships later in the article.
```js title="src/models/category.js"
i... | unknown | unknown | [Housekeeping > Refactoring `prepare`]
```
### Adding the `Category` model
We'll now create a `Category` model and a relevant `CategoryFactory` to match the rest of the implementation. We'll use this model as the main example for some of our relationships later in the article.
```js title="src/models/category.js"
i... | [Housekeeping > Refactoring `prepare`]
```
### Adding the `Category` model
We'll now create a `Category` model and a relevant `CategoryFactory` to match the rest of the implementation. We'll use this model as the main example for some of our relationships later in the article.
```js title="src/models/category.js"
i... | code_snippets | ||
c0fab504-5024-447a-b5dd-ee48158935e9 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 17 | SemanticChunker@1.0.0 | f9e7358aa95cea685ab1705f17035911dc6405b28e6bfc87d9661f4462ab7cac | [Relationship customization > Aliases]
### Aliases
If you were guessing we're going to implement **aliases** via the `as` property, you're absolutely right! This will allow us to define a **custom name** for the relationship attribute. Let's go ahead and modify the `prepare` method one last time.
```js title="src/co... | unknown | unknown | [Relationship customization > Aliases]
### Aliases
If you were guessing we're going to implement **aliases** via the `as` property, you're absolutely right! This will allow us to define a **custom name** for the relationship attribute. Let's go ahead and modify the `prepare` method one last time.
```js title="src/co... | [Relationship customization > Aliases]
### Aliases
If you were guessing we're going to implement **aliases** via the `as` property, you're absolutely right! This will allow us to define a **custom name** for the relationship attribute. Let's go ahead and modify the `prepare` method one last time.
```js title="src/co... | code_snippets | ||
cab10c00-8aaa-4ab7-b152-c69daa21c30b | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 20 | SemanticChunker@1.0.0 | c4e3474f4b00a4d32f8b52ab004dec098ec1eab7db9827d4b36150a3bed3ae10 | [Directory structure > Conclusion]
## Conclusion
After a long and winding road, we've finally implemented a very powerful **relationship system** for our models. We can now **define** relationships quickly and easily, **customize** them and even **implement self-referential relationships**. This is a very powerful se... | unknown | unknown | [Directory structure > Conclusion]
## Conclusion
After a long and winding road, we've finally implemented a very powerful **relationship system** for our models. We can now **define** relationships quickly and easily, **customize** them and even **implement self-referential relationships**. This is a very powerful se... | [Directory structure > Conclusion]
## Conclusion
After a long and winding road, we've finally implemented a very powerful **relationship system** for our models. We can now **define** relationships quickly and easily, **customize** them and even **implement self-referential relationships**. This is a very powerful se... | code_snippets | ||
cb6f3188-bd53-43df-89fa-7a63a35f2f41 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 14 | SemanticChunker@1.0.0 | 3d147b7d5a1cd89d22373749110fa9dccda10692e29c0e2d843a8ca1c5d688c3 | [Directory structure > Relationship customization]
## Relationship customization
So far so good, but **customization** is definitely going to be an issue in the long run. I want to create a taxonomy of categories, too. This will require categories that have a parent category, which is a category itself. This is a **s... | unknown | unknown | [Directory structure > Relationship customization]
## Relationship customization
So far so good, but **customization** is definitely going to be an issue in the long run. I want to create a taxonomy of categories, too. This will require categories that have a parent category, which is a category itself. This is a **s... | [Directory structure > Relationship customization]
## Relationship customization
So far so good, but **customization** is definitely going to be an issue in the long run. I want to create a taxonomy of categories, too. This will require categories that have a parent category, which is a category itself. This is a **s... | code_snippets | ||
cce18b9f-84d7-4fec-86e1-0aa8ed43bcd5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 6 | SemanticChunker@1.0.0 | af36a5570b88d579fe701ba0ea9016e2d5554cba857e5d728bc4a74379cc981e | [Directory structure > Relationship definitions]
## Relationship definitions
We've previously defined relationships via the use of a **field** that is then used by an **attribute method** to fetch the related records. This works alright, but **scaling** the project will become a bit of a hassle. We'll now introduce a... | unknown | unknown | [Directory structure > Relationship definitions]
## Relationship definitions
We've previously defined relationships via the use of a **field** that is then used by an **attribute method** to fetch the related records. This works alright, but **scaling** the project will become a bit of a hassle. We'll now introduce a... | [Directory structure > Relationship definitions]
## Relationship definitions
We've previously defined relationships via the use of a **field** that is then used by an **attribute method** to fetch the related records. This works alright, but **scaling** the project will become a bit of a hassle. We'll now introduce a... | code_snippets | ||
dc212480-0642-4190-823a-29055ea416a2 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 8 | SemanticChunker@1.0.0 | 005da35b2fd1b6738ac0ac78bf28ed4393689fabfd5417f3c3cafe6de2914d34 | [Relationship definitions > Belongs to]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel = Model.models[capitalize(target)];
return targetModel.find(this[foreignKey]);
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship type: ${relationshipType}`);
}
});
... | unknown | unknown | [Relationship definitions > Belongs to]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel = Model.models[capitalize(target)];
return targetModel.find(this[foreignKey]);
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship type: ${relationshipType}`);
}
});
... | [Relationship definitions > Belongs to]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel = Model.models[capitalize(target)];
return targetModel.find(this[foreignKey]);
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship type: ${relationshipType}`);
}
});
... | code_snippets | ||
dc7416a2-88d6-4805-a050-2970ac3df14c | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 18 | SemanticChunker@1.0.0 | a8a832e708efc18d6cf5d4c770abe3a9bc6656a99e7ec51c7894c9a3529eb9c1 | [Relationship customization > Aliases]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship type: $... | unknown | unknown | [Relationship customization > Aliases]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship type: $... | [Relationship customization > Aliases]
Object.defineProperty(model.prototype, propertyName, {
get() {
const targetModel =
Model.models[capitalize(toSingular(options.target))];
return targetModel.where({ [foreignKey]: this.id });
},
configurable: true,
});
} else {
throw new Error(`Invalid relationship type: $... | code_snippets | ||
dc861a9c-2513-44ae-945b-1a342c210c17 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 31 | SemanticChunker@1.0.0 | 9076f788e2fdcdc6cb55e614b0d1f813c8b7c950792fc420aaa2216aada473dc | [Directory structure > Addendum: Code summary]
```
```js title="src/serializers/postPreviewSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostPreviewSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['date', post => {
const date = new Date(post.publis... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/serializers/postPreviewSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostPreviewSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['date', post => {
const date = new Date(post.publis... | [Directory structure > Addendum: Code summary]
```
```js title="src/serializers/postPreviewSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostPreviewSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['date', post => {
const date = new Date(post.publis... | code_snippets | ||
e3b4ebba-85bb-4437-a16e-3fea7836d326 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 28 | SemanticChunker@1.0.0 | 428281eed5fcb709016432ed27b7415a35127e811aa8d76d882a0e21ae0b0855 | [Directory structure > Addendum: Code summary]
```
```js title="src/scripts/autoload.js"
import { readdir } from 'node:fs/promises';
import settings from '#src/config/settings.js';
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
const autoload = async () => {
const moduleMap = new Map();
f... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/scripts/autoload.js"
import { readdir } from 'node:fs/promises';
import settings from '#src/config/settings.js';
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
const autoload = async () => {
const moduleMap = new Map();
f... | [Directory structure > Addendum: Code summary]
```
```js title="src/scripts/autoload.js"
import { readdir } from 'node:fs/promises';
import settings from '#src/config/settings.js';
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
const autoload = async () => {
const moduleMap = new Map();
f... | code_snippets | ||
f818537d-eea1-427c-816e-e4af7fd6ea1c | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 5 | SemanticChunker@1.0.0 | f03ff58b6ad8c3e287d3acb236440d92908e9679a814e96d65f451ac622c019d | [Housekeeping > Refactoring `prepare`]
Now all of our posts are related to categories, much like they would in a real-world blogging setup. The relationship is **one-to-many**, where a post can belong to only one category, but a category can have many posts, same as it is with authors. | unknown | unknown | [Housekeeping > Refactoring `prepare`]
Now all of our posts are related to categories, much like they would in a real-world blogging setup. The relationship is **one-to-many**, where a post can belong to only one category, but a category can have many posts, same as it is with authors. | [Housekeeping > Refactoring `prepare`]
Now all of our posts are related to categories, much like they would in a real-world blogging setup. The relationship is **one-to-many**, where a post can belong to only one category, but a category can have many posts, same as it is with authors. | code_snippets | ||
f9871775-e44d-43a4-a5d2-d3b6e60780e6 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-advanced-relationships.md | unknown | 4577dbcd-77b4-4c45-9a20-c79f486299dd | 10 | SemanticChunker@1.0.0 | 8e4b9769a2fe5214052fdac7d9a78a5c2cff65d3ffbe1def694eb7ddf1c5f0c2 | [Relationship definitions > Has one]
### Has one
The previous code looks a lot tidier now and we can easily add more relationships in the future without having to worry about the implementation details. While we do not have any `hasOne` relationships in our current setup, we'll go ahead an implement the logic regardl... | unknown | unknown | [Relationship definitions > Has one]
### Has one
The previous code looks a lot tidier now and we can easily add more relationships in the future without having to worry about the implementation details. While we do not have any `hasOne` relationships in our current setup, we'll go ahead an implement the logic regardl... | [Relationship definitions > Has one]
### Has one
The previous code looks a lot tidier now and we can easily add more relationships in the future without having to worry about the implementation details. While we do not have any `hasOne` relationships in our current setup, we'll go ahead an implement the logic regardl... | code_snippets | ||
21460c7f-b96a-48f8-945e-ae86b094e981 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 23 | SemanticChunker@1.0.0 | ba13135410b241f536a906151380d58dad0515cb5a095321488b98f5c7680576 | [Directory structure > Addendum: Code summary]
```
```js title="src/models/post.js"
import Model from '#src/core/model.js';
import Author from '#src/models/author.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this, [
['title', { type: 'string', allowE... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/models/post.js"
import Model from '#src/core/model.js';
import Author from '#src/models/author.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this, [
['title', { type: 'string', allowE... | [Directory structure > Addendum: Code summary]
```
```js title="src/models/post.js"
import Model from '#src/core/model.js';
import Author from '#src/models/author.js';
export default class Post extends Model {
static {
// Prepare storage for the Post model
super.prepare(this, [
['title', { type: 'string', allowE... | code_snippets | ||
2a81d735-afc0-4fed-bbba-d567fcca03dd | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 0 | SemanticChunker@1.0.0 | 33fb655665e8c91102475c5e4452da33a7373643531d6b181745d26da1ea6449 | ---
title: Modeling complex JavaScript object autoloading and console
shortTitle: Complex object autoloading and console
language: javascript
tags: [object,class]
cover: digital-nomad-14
excerpt: In this installment, we'll create a custom object inspect utility to help us debug our complex objects in the console.
liste... | unknown | unknown | ---
title: Modeling complex JavaScript object autoloading and console
shortTitle: Complex object autoloading and console
language: javascript
tags: [object,class]
cover: digital-nomad-14
excerpt: In this installment, we'll create a custom object inspect utility to help us debug our complex objects in the console.
liste... | ---
title: Modeling complex JavaScript object autoloading and console
shortTitle: Complex object autoloading and console
language: javascript
tags: [object,class]
cover: digital-nomad-14
excerpt: In this installment, we'll create a custom object inspect utility to help us debug our complex objects in the console.
liste... | code_snippets | ||
362d9b57-d02c-4094-a6ae-2d8c17d95b6c | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 3 | SemanticChunker@1.0.0 | f99069221455cc00d8293299a5c64ffaec46f235c869ac392da03ea2a73e396a | [Autoloading modules > Settings]
### Settings
Before we dive into the autoloader, let's create a `settings.js` file in the `config` directory. This file will hold the **settings** for our project. For the time being, we'll simply define a setting for which modules to autoload.
```js title="src/config/settings.js"
co... | unknown | unknown | [Autoloading modules > Settings]
### Settings
Before we dive into the autoloader, let's create a `settings.js` file in the `config` directory. This file will hold the **settings** for our project. For the time being, we'll simply define a setting for which modules to autoload.
```js title="src/config/settings.js"
co... | [Autoloading modules > Settings]
### Settings
Before we dive into the autoloader, let's create a `settings.js` file in the `config` directory. This file will hold the **settings** for our project. For the time being, we'll simply define a setting for which modules to autoload.
```js title="src/config/settings.js"
co... | code_snippets | ||
3721420a-febd-4033-b05e-020456a70510 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 25 | SemanticChunker@1.0.0 | c8a701e02b34a36b9df01587468670371489ec4d0550adf1732dc0b46e501a96 | [Directory structure > Addendum: Code summary]
const base = {
id: idSequence,
title: titleSequence,
content: 'Post content',
};
const traits = {
published: {
publishedAt: new Date(),
},
unpublished: {
publishedAt: null,
},
};
export default class PostFactory extends Factory {
static {
super.prepare(this, ... | unknown | unknown | [Directory structure > Addendum: Code summary]
const base = {
id: idSequence,
title: titleSequence,
content: 'Post content',
};
const traits = {
published: {
publishedAt: new Date(),
},
unpublished: {
publishedAt: null,
},
};
export default class PostFactory extends Factory {
static {
super.prepare(this, ... | [Directory structure > Addendum: Code summary]
const base = {
id: idSequence,
title: titleSequence,
content: 'Post content',
};
const traits = {
published: {
publishedAt: new Date(),
},
unpublished: {
publishedAt: null,
},
};
export default class PostFactory extends Factory {
static {
super.prepare(this, ... | code_snippets | ||
3828730b-a49e-43f6-a913-6aa1a53be106 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 13 | SemanticChunker@1.0.0 | c1fd208eaa3be4b51e60055e0909d81dd99c3c14c97d62c7e473c4b2b02014df | [Object inspection > Inspectable fields]
```
This simple change ensures that only fields marked as `inspectable` (defaults to `true` for all fields) are displayed in the console. We can then go ahead and mark the `Author` model's `email` field as not inspectable.
```js title="src/models/author.js"
import Model from ... | unknown | unknown | [Object inspection > Inspectable fields]
```
This simple change ensures that only fields marked as `inspectable` (defaults to `true` for all fields) are displayed in the console. We can then go ahead and mark the `Author` model's `email` field as not inspectable.
```js title="src/models/author.js"
import Model from ... | [Object inspection > Inspectable fields]
```
This simple change ensures that only fields marked as `inspectable` (defaults to `true` for all fields) are displayed in the console. We can then go ahead and mark the `Author` model's `email` field as not inspectable.
```js title="src/models/author.js"
import Model from ... | code_snippets | ||
41298afe-9374-4902-8bd1-cef20b24b377 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 7 | SemanticChunker@1.0.0 | d92799b4fa0a6a6556f10ed9b684218eedb4bee1c69702903491f63907d295b2 | [Console environment > Console script]
### Console script
The `console.js` script will be the entry point for our console environment. It will **import the autoloaded modules** and **set up the REPL**. For that last part, we'll iterate over the modules and make them available in the REPL context.
```js title="src/sc... | unknown | unknown | [Console environment > Console script]
### Console script
The `console.js` script will be the entry point for our console environment. It will **import the autoloaded modules** and **set up the REPL**. For that last part, we'll iterate over the modules and make them available in the REPL context.
```js title="src/sc... | [Console environment > Console script]
### Console script
The `console.js` script will be the entry point for our console environment. It will **import the autoloaded modules** and **set up the REPL**. For that last part, we'll iterate over the modules and make them available in the REPL context.
```js title="src/sc... | code_snippets | ||
44725e71-a09a-43d4-b165-0747adbe4e54 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 22 | SemanticChunker@1.0.0 | 428281eed5fcb709016432ed27b7415a35127e811aa8d76d882a0e21ae0b0855 | [Directory structure > Addendum: Code summary]
```
```js title="src/scripts/autoload.js"
import { readdir } from 'node:fs/promises';
import settings from '#src/config/settings.js';
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
const autoload = async () => {
const moduleMap = new Map();
f... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/scripts/autoload.js"
import { readdir } from 'node:fs/promises';
import settings from '#src/config/settings.js';
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
const autoload = async () => {
const moduleMap = new Map();
f... | [Directory structure > Addendum: Code summary]
```
```js title="src/scripts/autoload.js"
import { readdir } from 'node:fs/promises';
import settings from '#src/config/settings.js';
const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
const autoload = async () => {
const moduleMap = new Map();
f... | code_snippets | ||
45e0fd3c-f66c-4993-b2fb-d9dc60fe5a91 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 4 | SemanticChunker@1.0.0 | 59d5853f77d5987b1b21b17ef8cf0a0aeb598b539435ca9b61e1ab77dfc220ce | [Autoloading modules > Settings]
```
> [!NOTE]
>
> While the settings file might be a bit of an overkill for what appears to be a single setting, it's a good practice to have a **central place for all the settings**. This way, you can easily add more settings as your project grows.
### Autoloader
One of the feature... | unknown | unknown | [Autoloading modules > Settings]
```
> [!NOTE]
>
> While the settings file might be a bit of an overkill for what appears to be a single setting, it's a good practice to have a **central place for all the settings**. This way, you can easily add more settings as your project grows.
### Autoloader
One of the feature... | [Autoloading modules > Settings]
```
> [!NOTE]
>
> While the settings file might be a bit of an overkill for what appears to be a single setting, it's a good practice to have a **central place for all the settings**. This way, you can easily add more settings as your project grows.
### Autoloader
One of the feature... | code_snippets | ||
4685562d-7689-464e-9885-f6ba440ae4ec | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 11 | SemanticChunker@1.0.0 | fd4b64c5b970d2c898357294a3b8c4bc3ba989b0e80e87a9be5f8acd9d801c51 | [Object inspection > Hexadecimal id string]
### Hexadecimal id string
One more thing we can do is **convert the id to a hexadecimal string**. This is more of a cosmetic change, but it can make the output look a little bit cleaner.
All this takes is the use of `Number.prototype.toString()` with a `16` radix and `Stri... | unknown | unknown | [Object inspection > Hexadecimal id string]
### Hexadecimal id string
One more thing we can do is **convert the id to a hexadecimal string**. This is more of a cosmetic change, but it can make the output look a little bit cleaner.
All this takes is the use of `Number.prototype.toString()` with a `16` radix and `Stri... | [Object inspection > Hexadecimal id string]
### Hexadecimal id string
One more thing we can do is **convert the id to a hexadecimal string**. This is more of a cosmetic change, but it can make the output look a little bit cleaner.
All this takes is the use of `Number.prototype.toString()` with a `16` radix and `Stri... | code_snippets | ||
4d7c3b7e-3f61-421d-bd56-bd127849d3e0 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 19 | SemanticChunker@1.0.0 | e7c8f719e78e8f1b4094ea313d519fc4f0b4803e5b973a0a9f98506f21ae83b5 | [Directory structure > Addendum: Code summary]
// If single value, use strict equality
return record[key] === query[key];
});
})
);
}
order(comparator) {
return RecordSet.from(this.sort(comparator));
}
pluck(attribute) {
return RecordSet.from(super.map(record => record[attribute]))
}
select(...attribute... | unknown | unknown | [Directory structure > Addendum: Code summary]
// If single value, use strict equality
return record[key] === query[key];
});
})
);
}
order(comparator) {
return RecordSet.from(this.sort(comparator));
}
pluck(attribute) {
return RecordSet.from(super.map(record => record[attribute]))
}
select(...attribute... | [Directory structure > Addendum: Code summary]
// If single value, use strict equality
return record[key] === query[key];
});
})
);
}
order(comparator) {
return RecordSet.from(this.sort(comparator));
}
pluck(attribute) {
return RecordSet.from(super.map(record => record[attribute]))
}
select(...attribute... | code_snippets | ||
67ba42df-884b-4925-a4e6-a011110ff38c | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 24 | SemanticChunker@1.0.0 | a05076445e52ed01c59d7cb7f3da1fbb49fe5419e2579825aadfadea19a3bf9b | [Directory structure > Addendum: Code summary]
```
```js title="src/serializers/postSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['content', post => `<p>${post.content}</p>`],
['date', post => {
... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/serializers/postSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['content', post => `<p>${post.content}</p>`],
['date', post => {
... | [Directory structure > Addendum: Code summary]
```
```js title="src/serializers/postSerializer.js"
import Serializer from '#src/core/serializer.js';
export default class PostSerializer extends Serializer {
static {
super.prepare(this, [
'title',
['content', post => `<p>${post.content}</p>`],
['date', post => {
... | code_snippets | ||
6c12021d-322b-4f04-a919-3081ff66ffee | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 2 | SemanticChunker@1.0.0 | 9af0e21049c0a2140346f83528e6d07ada06a18e283dbcd93951c4a1930ab9b9 | [Directory structure > Autoloading modules]
## Autoloading modules
While developing the project up until this point, I've used Node.js and its [REPL](https://nodejs.org/api/repl.html) to interact with the objects. However, I've found it cumbersome to require all the modules manually. This concern will only get more s... | unknown | unknown | [Directory structure > Autoloading modules]
## Autoloading modules
While developing the project up until this point, I've used Node.js and its [REPL](https://nodejs.org/api/repl.html) to interact with the objects. However, I've found it cumbersome to require all the modules manually. This concern will only get more s... | [Directory structure > Autoloading modules]
## Autoloading modules
While developing the project up until this point, I've used Node.js and its [REPL](https://nodejs.org/api/repl.html) to interact with the objects. However, I've found it cumbersome to require all the modules manually. This concern will only get more s... | code_snippets | ||
76982f09-e38b-41db-9ee1-892fe0a638d8 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 8 | SemanticChunker@1.0.0 | 2573b801516ee3df85af1207d15aa0879f749da381e6607ebab2570ecb163921 | [Directory structure > Object inspection]
## Object inspection
The previous output is alright, but when our models inevitably become huge, we might wish we had customized the **object inspection**. Luckily, Node.js provides a way to do just that, using the [`util.inspect.custom`](https://nodejs.org/api/util.html#util... | unknown | unknown | [Directory structure > Object inspection]
## Object inspection
The previous output is alright, but when our models inevitably become huge, we might wish we had customized the **object inspection**. Luckily, Node.js provides a way to do just that, using the [`util.inspect.custom`](https://nodejs.org/api/util.html#util... | [Directory structure > Object inspection]
## Object inspection
The previous output is alright, but when our models inevitably become huge, we might wish we had customized the **object inspection**. Luckily, Node.js provides a way to do just that, using the [`util.inspect.custom`](https://nodejs.org/api/util.html#util... | code_snippets | ||
83c1e51a-df30-4af6-92c0-10d61511ecaf | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 5 | SemanticChunker@1.0.0 | c3563a152e4eb69ec055feb70dc9d64d155e57348f9bde761d9f5298649537be | [Autoloading modules > Settings]
> [!NOTE]
>
> As you'll notice, this implementation is pretty barebones, as it only handles **single-level directories** and **single-export modules**. However, it's a good starting point for a small project. You can take a stab at improving it by adding more features, such as nested d... | unknown | unknown | [Autoloading modules > Settings]
> [!NOTE]
>
> As you'll notice, this implementation is pretty barebones, as it only handles **single-level directories** and **single-export modules**. However, it's a good starting point for a small project. You can take a stab at improving it by adding more features, such as nested d... | [Autoloading modules > Settings]
> [!NOTE]
>
> As you'll notice, this implementation is pretty barebones, as it only handles **single-level directories** and **single-export modules**. However, it's a good starting point for a small project. You can take a stab at improving it by adding more features, such as nested d... | code_snippets | ||
9ad5de42-7c3b-4474-a36c-fe1414ec3dad | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 21 | SemanticChunker@1.0.0 | 9461035fe6d73f5d858ff015f4574fcf90da0ef03967ea4b936c9b7866b1c2a8 | [Directory structure > Addendum: Code summary]
Object.keys(base).forEach(key => {
const value = base[key];
const getter = isSequence(value) ? value[sequenceSymbol] : () => value;
Object.defineProperty(factoryBase, key, {
get: getter,
enumerable: true,
});
});
if (!Factory.modelMap.has(modelName))
Factory.mod... | unknown | unknown | [Directory structure > Addendum: Code summary]
Object.keys(base).forEach(key => {
const value = base[key];
const getter = isSequence(value) ? value[sequenceSymbol] : () => value;
Object.defineProperty(factoryBase, key, {
get: getter,
enumerable: true,
});
});
if (!Factory.modelMap.has(modelName))
Factory.mod... | [Directory structure > Addendum: Code summary]
Object.keys(base).forEach(key => {
const value = base[key];
const getter = isSequence(value) ? value[sequenceSymbol] : () => value;
Object.defineProperty(factoryBase, key, {
get: getter,
enumerable: true,
});
});
if (!Factory.modelMap.has(modelName))
Factory.mod... | code_snippets | ||
9d881b2b-9ee1-45eb-acb7-3d71fe618e33 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 18 | SemanticChunker@1.0.0 | 0f16a6f3de5829f1e83e93a8c4fed52b58f588df4dc070538f5e419cfe2e856a | [Directory structure > Addendum: Code summary]
```
# [continued: part 2]
static where(query) {
return this.all.where(query);
}
static order(comparator) {
return this.all.order(comparator);
}
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
r... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
# [continued: part 2]
static where(query) {
return this.all.where(query);
}
static order(comparator) {
return this.all.order(comparator);
}
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
r... | [Directory structure > Addendum: Code summary]
```
# [continued: part 2]
static where(query) {
return this.all.where(query);
}
static order(comparator) {
return this.all.order(comparator);
}
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
r... | code_snippets | ||
aca1ec29-fbb3-49e7-a16d-e78aa0ce55d5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 10 | SemanticChunker@1.0.0 | 46d0807bd360b181d6d37c2a1a0b51a44f8017780877a19fce28275b5f1a48d6 | [Object inspection > Handling nesting]
### Handling nesting
The output is already looking better, but we can still improve it. For instance, if we have an array of `Post` records, we might want to see the records compactly displayed.
You might have noticed the `depth` parameter from the previous method. We can use i... | unknown | unknown | [Object inspection > Handling nesting]
### Handling nesting
The output is already looking better, but we can still improve it. For instance, if we have an array of `Post` records, we might want to see the records compactly displayed.
You might have noticed the `depth` parameter from the previous method. We can use i... | [Object inspection > Handling nesting]
### Handling nesting
The output is already looking better, but we can still improve it. For instance, if we have an array of `Post` records, we might want to see the records compactly displayed.
You might have noticed the `depth` parameter from the previous method. We can use i... | code_snippets | ||
b85a730e-9dc0-4238-becf-2c348d4c0f07 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 6 | SemanticChunker@1.0.0 | bfe929f64add5e8ee74c2e579cb5903d4a68f7a1403db0915ea9d46912b22fae | [Directory structure > Console environment]
## Console environment
With the autoloader in place, we can now focus on creating a **console environment** to interact with our objects. We'll start by setting up the `console.js` script, then we'll create a custom object inspect utility. | unknown | unknown | [Directory structure > Console environment]
## Console environment
With the autoloader in place, we can now focus on creating a **console environment** to interact with our objects. We'll start by setting up the `console.js` script, then we'll create a custom object inspect utility. | [Directory structure > Console environment]
## Console environment
With the autoloader in place, we can now focus on creating a **console environment** to interact with our objects. We'll start by setting up the `console.js` script, then we'll create a custom object inspect utility. | code_snippets | ||
cdf532c2-45c1-4e4b-888b-726393f9e359 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 14 | SemanticChunker@1.0.0 | 7c4313c67eb4cf62821b9900287a272c9dbef98ae6c3231d720d98c05c72dc7d | [Directory structure > Conclusion]
## Conclusion
Our ActiveRecord-inspired project is starting to address the pains of scaling. We can finally easily **load all the modules** and interact with them in the **console**. We've also created a custom **object inspect utility** to help us debug our complex objects and hide... | unknown | unknown | [Directory structure > Conclusion]
## Conclusion
Our ActiveRecord-inspired project is starting to address the pains of scaling. We can finally easily **load all the modules** and interact with them in the **console**. We've also created a custom **object inspect utility** to help us debug our complex objects and hide... | [Directory structure > Conclusion]
## Conclusion
Our ActiveRecord-inspired project is starting to address the pains of scaling. We can finally easily **load all the modules** and interact with them in the **console**. We've also created a custom **object inspect utility** to help us debug our complex objects and hide... | code_snippets | ||
d3cbde59-a804-4af8-8926-121ba636ae97 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 20 | SemanticChunker@1.0.0 | 027acc623f60e21bd839c1bbede5b484bcdcf52226c4216dd52341f40ae0ead1 | [Directory structure > Addendum: Code summary]
```
```js title="src/core/serializer.js"
export default class Serializer {
static prepare(serializer, serializableAttributes) {
serializer.serializableAttributes = [];
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const a... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/core/serializer.js"
export default class Serializer {
static prepare(serializer, serializableAttributes) {
serializer.serializableAttributes = [];
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const a... | [Directory structure > Addendum: Code summary]
```
```js title="src/core/serializer.js"
export default class Serializer {
static prepare(serializer, serializableAttributes) {
serializer.serializableAttributes = [];
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const a... | code_snippets | ||
e46918e1-47ad-476c-9dea-886eb9a5dee7 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 1 | SemanticChunker@1.0.0 | 71c7606d4f660591dd94187c445bdcfd2309c10d27c0885e881d1a183c4f576e | [Directory structure]
## Directory structure
This time, we're expanding the directory structure just a little. We'll add a new `config` directory for **settings** and a `scripts` directory for our **autoload** and **console** scripts.
```plaintext
src/
├── config/
│ └── settings.js
├── core/
│ ├── model.js
│ ├── rec... | unknown | unknown | [Directory structure]
## Directory structure
This time, we're expanding the directory structure just a little. We'll add a new `config` directory for **settings** and a `scripts` directory for our **autoload** and **console** scripts.
```plaintext
src/
├── config/
│ └── settings.js
├── core/
│ ├── model.js
│ ├── rec... | [Directory structure]
## Directory structure
This time, we're expanding the directory structure just a little. We'll add a new `config` directory for **settings** and a `scripts` directory for our **autoload** and **console** scripts.
```plaintext
src/
├── config/
│ └── settings.js
├── core/
│ ├── model.js
│ ├── rec... | code_snippets | ||
e4e30b1f-d188-4e0d-8980-d45d348f19bb | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 12 | SemanticChunker@1.0.0 | 27c2d41441138048fa68478e072815d5178ffd9cd31bdebf4cbc767721f7634b | [Object inspection > Inspectable fields]
### Inspectable fields
So far, all of the fields in our models have been inspectable, which is the default behavior. However, we might want to **hide some fields** from the inspection. Say, for instance, that we have a `password` field or some personal data that is sensitive a... | unknown | unknown | [Object inspection > Inspectable fields]
### Inspectable fields
So far, all of the fields in our models have been inspectable, which is the default behavior. However, we might want to **hide some fields** from the inspection. Say, for instance, that we have a `password` field or some personal data that is sensitive a... | [Object inspection > Inspectable fields]
### Inspectable fields
So far, all of the fields in our models have been inspectable, which is the default behavior. However, we might want to **hide some fields** from the inspection. Say, for instance, that we have a `password` field or some personal data that is sensitive a... | code_snippets | ||
e59eb6cc-5d77-44e6-8cca-39ac03ee7548 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 9 | SemanticChunker@1.0.0 | d88496a2ad0de285429a4a279c4e90492daa16b7e823590c5c2db9524f6c9e6d | [Object inspection > Custom object inspect utility]
### Custom object inspect utility
In order to **make our records stand out**, we'll start by adding a custom value to [`util.inspect.styles`](https://nodejs.org/api/util.html#customizing-utilinspect-colors), called `record` and set it to `blue` (as far as I can tell... | unknown | unknown | [Object inspection > Custom object inspect utility]
### Custom object inspect utility
In order to **make our records stand out**, we'll start by adding a custom value to [`util.inspect.styles`](https://nodejs.org/api/util.html#customizing-utilinspect-colors), called `record` and set it to `blue` (as far as I can tell... | [Object inspection > Custom object inspect utility]
### Custom object inspect utility
In order to **make our records stand out**, we'll start by adding a custom value to [`util.inspect.styles`](https://nodejs.org/api/util.html#customizing-utilinspect-colors), called `record` and set it to `blue` (as far as I can tell... | code_snippets | ||
ede866d2-8147-4cda-b742-8b7a1ec02f8c | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 17 | SemanticChunker@1.0.0 | 5ca806f3d23c0aa24f42c05b04e12878dcef9a4f9ca6e3a1bb044e2d98a5dc61 | [Directory structure > Addendum: Code summary]
```
# [continued: part 1]
let fieldChecker = fieldTypeChecker;
if (unique) {
model.indexes.push(fieldName);
const uniqueChecker = value =>
!Model.indexedInstances[name][fieldName].has(value);
fieldChecker = value => fieldTypeChecker(value) && uniqueChecker(value)... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
# [continued: part 1]
let fieldChecker = fieldTypeChecker;
if (unique) {
model.indexes.push(fieldName);
const uniqueChecker = value =>
!Model.indexedInstances[name][fieldName].has(value);
fieldChecker = value => fieldTypeChecker(value) && uniqueChecker(value)... | [Directory structure > Addendum: Code summary]
```
# [continued: part 1]
let fieldChecker = fieldTypeChecker;
if (unique) {
model.indexes.push(fieldName);
const uniqueChecker = value =>
!Model.indexedInstances[name][fieldName].has(value);
fieldChecker = value => fieldTypeChecker(value) && uniqueChecker(value)... | code_snippets | ||
f5f0400a-5e74-4984-b4b8-800421498129 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 15 | SemanticChunker@1.0.0 | cbeeed21ccf46fd960e4a61e8200229d79d7d5e64364d2292c28da10b4355009 | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
The customary code summary of the entire implementation up until this point can be found below. Make sure to bookmark it, if you need a quick reference in the future.
You can also [browse through the Code Reference on GitHub](https://github.com... | unknown | unknown | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
The customary code summary of the entire implementation up until this point can be found below. Make sure to bookmark it, if you need a quick reference in the future.
You can also [browse through the Code Reference on GitHub](https://github.com... | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
The customary code summary of the entire implementation up until this point can be found below. Make sure to bookmark it, if you need a quick reference in the future.
You can also [browse through the Code Reference on GitHub](https://github.com... | code_snippets | ||
ff454ebd-5647-427f-b28f-309b88ca3848 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-autoloading-console.md | unknown | 04c07f95-4d2b-45f9-b243-05a2d0b72576 | 16 | SemanticChunker@1.0.0 | b449c9bf5025e9e56dae54308849c61802d6932a85cd8517a599fbbd0c6476f9 | [Directory structure > Addendum: Code summary]
```
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
import util from 'util';
util.inspect.styles.record = 'blue';
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
export default class Model {
static instances = {};... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
import util from 'util';
util.inspect.styles.record = 'blue';
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
export default class Model {
static instances = {};... | [Directory structure > Addendum: Code summary]
```
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
import util from 'util';
util.inspect.styles.record = 'blue';
const customInspectSymbol = Symbol.for('nodejs.util.inspect.custom');
export default class Model {
static instances = {};... | code_snippets |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.