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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6149e08c-1a43-426d-8499-81d01c47cb42 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 3 | SemanticChunker@1.0.0 | 6c4f5aa32632abb800bc727010563feace66d0598e3a1d7c9ad813aa73b94aad | [Scope definitions > Filtering scopes]
### Filtering scopes
Due to the way, we've implemented our querying system, scopes can be easily defined, yet the **syntax** won't be too similar to that of ActiveRecord. I honestly don't mind this too much, due to the fact that it may make searching for scope usage a little eas... | unknown | unknown | [Scope definitions > Filtering scopes]
### Filtering scopes
Due to the way, we've implemented our querying system, scopes can be easily defined, yet the **syntax** won't be too similar to that of ActiveRecord. I honestly don't mind this too much, due to the fact that it may make searching for scope usage a little eas... | [Scope definitions > Filtering scopes]
### Filtering scopes
Due to the way, we've implemented our querying system, scopes can be easily defined, yet the **syntax** won't be too similar to that of ActiveRecord. I honestly don't mind this too much, due to the fact that it may make searching for scope usage a little eas... | code_snippets | ||
774618e5-6511-4c04-b2ee-152f38d723e3 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 0 | SemanticChunker@1.0.0 | cfde5dafcf9b642445bb59eba83fd0f5701c39a9ebbc0faedf82ec20e34bc274 | ---
title: Modeling complex JavaScript object scopes
shortTitle: Complex object scopes
language: javascript
tags: [object,class]
cover: digital-nomad-13
excerpt: In the third installment of implementing an ActiveRecord-like pattern in JavaScript, we'll model and optimize object scoping.
listed: true
dateModified: 2024-... | unknown | unknown | ---
title: Modeling complex JavaScript object scopes
shortTitle: Complex object scopes
language: javascript
tags: [object,class]
cover: digital-nomad-13
excerpt: In the third installment of implementing an ActiveRecord-like pattern in JavaScript, we'll model and optimize object scoping.
listed: true
dateModified: 2024-... | ---
title: Modeling complex JavaScript object scopes
shortTitle: Complex object scopes
language: javascript
tags: [object,class]
cover: digital-nomad-13
excerpt: In the third installment of implementing an ActiveRecord-like pattern in JavaScript, we'll model and optimize object scoping.
listed: true
dateModified: 2024-... | code_snippets | ||
7f9f05d6-c915-4e69-aabc-5bf32c526df2 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 5 | SemanticChunker@1.0.0 | 4a02059e772c871426581ee9e1f9b17a981f427e40ad1a149b00389ff61a0b54 | [Directory structure > Scope chaining]
## Scope chaining
Now that we have some scopes defined, we can try **chaining** them together. This will allow us to create more complex queries by combining multiple scopes. As scopes are named functions, complex logic can be collapsed into a few keywords, helping future mainta... | unknown | unknown | [Directory structure > Scope chaining]
## Scope chaining
Now that we have some scopes defined, we can try **chaining** them together. This will allow us to create more complex queries by combining multiple scopes. As scopes are named functions, complex logic can be collapsed into a few keywords, helping future mainta... | [Directory structure > Scope chaining]
## Scope chaining
Now that we have some scopes defined, we can try **chaining** them together. This will allow us to create more complex queries by combining multiple scopes. As scopes are named functions, complex logic can be collapsed into a few keywords, helping future mainta... | code_snippets | ||
b10c4083-76ef-46d6-b670-af9b3cf3b0fa | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 11 | SemanticChunker@1.0.0 | 71ffa5c3b0ec6cedec48df76dc4564f470c3d7b3a086ff77b091bdbf2f306075 | [Directory structure > Conclusion]
## Conclusion
As per previous installments, we continue our journey to implement an ActiveRecord-like pattern in JavaScript. This time around, we've focused on making repeated queries more efficient and easier to read. We've implemented scopes, which are predefined queries that can ... | unknown | unknown | [Directory structure > Conclusion]
## Conclusion
As per previous installments, we continue our journey to implement an ActiveRecord-like pattern in JavaScript. This time around, we've focused on making repeated queries more efficient and easier to read. We've implemented scopes, which are predefined queries that can ... | [Directory structure > Conclusion]
## Conclusion
As per previous installments, we continue our journey to implement an ActiveRecord-like pattern in JavaScript. This time around, we've focused on making repeated queries more efficient and easier to read. We've implemented scopes, which are predefined queries that can ... | code_snippets | ||
b720b9ae-0ae2-4ea9-82e5-7e8726923fca | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 2 | SemanticChunker@1.0.0 | 3ad890084ed8a5713f4ae23ca5abd1479af43956b943dff960a5067601b0dcc8 | [Directory structure > Scope definitions]
## Scope definitions
ActiveRecord has a concept called **scopes**, which are **predefined queries** that can be reused. These are usually defined in a model and can be chained together to create more complex queries. They provide convenient ways to make your code DRY (Don't R... | unknown | unknown | [Directory structure > Scope definitions]
## Scope definitions
ActiveRecord has a concept called **scopes**, which are **predefined queries** that can be reused. These are usually defined in a model and can be chained together to create more complex queries. They provide convenient ways to make your code DRY (Don't R... | [Directory structure > Scope definitions]
## Scope definitions
ActiveRecord has a concept called **scopes**, which are **predefined queries** that can be reused. These are usually defined in a model and can be chained together to create more complex queries. They provide convenient ways to make your code DRY (Don't R... | code_snippets | ||
c674a021-bbd1-431d-9618-8481d9090931 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 13 | SemanticChunker@1.0.0 | 45307648f2639c10f98eda1431eb7ba5782ee49ec876d7b14e9478ed08c377c7 | [Directory structure > Addendum: Code summary]
// Store the instance in the instances and indexedInstances
Model.instances[modelName].push(this);
Model.indexedInstances[modelName].set(data.id, this);
}
static get all() {
return RecordSet.from(Model.instances[this.name] || []);
}
static where(query) {
return ... | unknown | unknown | [Directory structure > Addendum: Code summary]
// Store the instance in the instances and indexedInstances
Model.instances[modelName].push(this);
Model.indexedInstances[modelName].set(data.id, this);
}
static get all() {
return RecordSet.from(Model.instances[this.name] || []);
}
static where(query) {
return ... | [Directory structure > Addendum: Code summary]
// Store the instance in the instances and indexedInstances
Model.instances[modelName].push(this);
Model.indexedInstances[modelName].set(data.id, this);
}
static get all() {
return RecordSet.from(Model.instances[this.name] || []);
}
static where(query) {
return ... | code_snippets | ||
dbd283c5-dbe5-4dc9-9915-4ffa933cda7b | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 7 | SemanticChunker@1.0.0 | 55100b7533095b854744dee3214b794f357548677d18d5a3735c52e81f7abad4 | [Scope chaining > Model-level scopes]
### Model-level scopes
If you noticed that the strange decisions to pass a `records` argument to the scopes, you're about to find out why. This decision allows us to create a simpler chaining system in the `Model` class itself. All we'll need is a `scope` method that takes a list... | unknown | unknown | [Scope chaining > Model-level scopes]
### Model-level scopes
If you noticed that the strange decisions to pass a `records` argument to the scopes, you're about to find out why. This decision allows us to create a simpler chaining system in the `Model` class itself. All we'll need is a `scope` method that takes a list... | [Scope chaining > Model-level scopes]
### Model-level scopes
If you noticed that the strange decisions to pass a `records` argument to the scopes, you're about to find out why. This decision allows us to create a simpler chaining system in the `Model` class itself. All we'll need is a `scope` method that takes a list... | code_snippets | ||
ebf50f10-56e0-4f49-9fdc-16b0bb181852 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 10 | SemanticChunker@1.0.0 | 7b171bd0ac6aa69dfa2dbfde67efecc8676e8a2730eff5ebea5deade84aa5ef8 | [Directory structure > Attribute caching]
This code looks intimidating even to me, not gonna lie. But it's the only change we'll have to make. In the `prepare` method, we now create a `WeakMap` for **each getter function on the model**. This map will cache the calculated attribute for each instance, making subsequent ... | unknown | unknown | [Directory structure > Attribute caching]
This code looks intimidating even to me, not gonna lie. But it's the only change we'll have to make. In the `prepare` method, we now create a `WeakMap` for **each getter function on the model**. This map will cache the calculated attribute for each instance, making subsequent ... | [Directory structure > Attribute caching]
This code looks intimidating even to me, not gonna lie. But it's the only change we'll have to make. In the `prepare` method, we now create a `WeakMap` for **each getter function on the model**. This map will cache the calculated attribute for each instance, making subsequent ... | code_snippets | ||
f9043b08-8c6d-4764-87a8-e3de857e8893 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 4 | SemanticChunker@1.0.0 | 2508a7e6563a5246af4c83dee34e9c5fe08aa6ce7bd4fcb2b4dcdcae8fe4a3ed | [Scope definitions > Sorting scopes]
### Sorting scopes
Apart from filtering records, we may also want to sort them. Before we do that, however, I'd like to add an `order` method to our `RecordSet` class. It's not much more than an alias for `Array.prototype.sort()`, but I prefer naming things explicitly. This way we... | unknown | unknown | [Scope definitions > Sorting scopes]
### Sorting scopes
Apart from filtering records, we may also want to sort them. Before we do that, however, I'd like to add an `order` method to our `RecordSet` class. It's not much more than an alias for `Array.prototype.sort()`, but I prefer naming things explicitly. This way we... | [Scope definitions > Sorting scopes]
### Sorting scopes
Apart from filtering records, we may also want to sort them. Before we do that, however, I'd like to add an `order` method to our `RecordSet` class. It's not much more than an alias for `Array.prototype.sort()`, but I prefer naming things explicitly. This way we... | code_snippets | ||
fbd27214-592c-47b6-961b-282e019631d2 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-scopes.md | unknown | 86af772d-5755-4b58-894c-26f243c26da6 | 1 | SemanticChunker@1.0.0 | d68ee4ec63128ee509b03497aec0f998717ede6fefa8dc35589339514ee2a6b2 | [Directory structure]
## Directory structure
Before we dive into the code, let's take a look at the current directory structure:
```plaintext
src/
├── core/
│ ├── model.js
│ └── recordSet.js
└── models/
├── author.js
└── post.js
```
This time around, we won't be making any changes to the structure, but rather to ... | unknown | unknown | [Directory structure]
## Directory structure
Before we dive into the code, let's take a look at the current directory structure:
```plaintext
src/
├── core/
│ ├── model.js
│ └── recordSet.js
└── models/
├── author.js
└── post.js
```
This time around, we won't be making any changes to the structure, but rather to ... | [Directory structure]
## Directory structure
Before we dive into the code, let's take a look at the current directory structure:
```plaintext
src/
├── core/
│ ├── model.js
│ └── recordSet.js
└── models/
├── author.js
└── post.js
```
This time around, we won't be making any changes to the structure, but rather to ... | code_snippets | ||
073757ea-1d46-45e9-9007-c79ced2c6af2 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 12 | SemanticChunker@1.0.0 | 4960c44a12e760f12bae21b76d8b31837e05d0d481a4cf7b9d8c2420c9df4ff8 | [Advanced querying > Querying calculated attributes]
### Querying calculated attributes
Calculated attributes are implemented as getter functions, which means our `where` method can directly query them any way we like. Same goes for `pluck` and `select`, as well as built-in array methods, such as `Array.prototype.map... | unknown | unknown | [Advanced querying > Querying calculated attributes]
### Querying calculated attributes
Calculated attributes are implemented as getter functions, which means our `where` method can directly query them any way we like. Same goes for `pluck` and `select`, as well as built-in array methods, such as `Array.prototype.map... | [Advanced querying > Querying calculated attributes]
### Querying calculated attributes
Calculated attributes are implemented as getter functions, which means our `where` method can directly query them any way we like. Same goes for `pluck` and `select`, as well as built-in array methods, such as `Array.prototype.map... | code_snippets | ||
422e9b4f-fefd-4fb4-8bdc-2b97872ee39a | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 9 | SemanticChunker@1.0.0 | a42dfb12206f4e3ebedf482f65f19b0d772966c1856c68c9af53762f72b98d9f | [Model relationships > Multiple relationships]
### Multiple relationships
As you may have noticed, I skipped adding the **other side of the relationship** in the previous section. This means that no `Author` instance can easily retrieve all the posts written by that author.
This, however, is a case of a multiple rel... | unknown | unknown | [Model relationships > Multiple relationships]
### Multiple relationships
As you may have noticed, I skipped adding the **other side of the relationship** in the previous section. This means that no `Author` instance can easily retrieve all the posts written by that author.
This, however, is a case of a multiple rel... | [Model relationships > Multiple relationships]
### Multiple relationships
As you may have noticed, I skipped adding the **other side of the relationship** in the previous section. This means that no `Author` instance can easily retrieve all the posts written by that author.
This, however, is a case of a multiple rel... | code_snippets | ||
44d9e40c-934d-4220-8e33-ea9f8ebd1f6e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 2 | SemanticChunker@1.0.0 | 0ef13d1445cd805a702b3ab8132ff156a2b0cf75fce2734c9053e1fb9b84987b | [Directory structure > Model attributes]
## Model attributes
In the ActiveRecord pattern, models have attributes that represent the columns in the database. Models can also define methods which act very similarly to attributes, allowing us to retrieve data that may be the result of more complex operations on the mode... | unknown | unknown | [Directory structure > Model attributes]
## Model attributes
In the ActiveRecord pattern, models have attributes that represent the columns in the database. Models can also define methods which act very similarly to attributes, allowing us to retrieve data that may be the result of more complex operations on the mode... | [Directory structure > Model attributes]
## Model attributes
In the ActiveRecord pattern, models have attributes that represent the columns in the database. Models can also define methods which act very similarly to attributes, allowing us to retrieve data that may be the result of more complex operations on the mode... | code_snippets | ||
48ef528a-1f02-4d43-90e4-e2aedffc1b88 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 17 | SemanticChunker@1.0.0 | 0cf01caa35b3974212e5f1ab4d0074642af1778ba6429ef5995ccee3941b386f | [Advanced querying > Optimizing `id` queries]
constructor(data) {
super(data);
this.id = data.id;
this.name = data.name;
this.surname = data.surname;
this.email = data.email;
}
get fullName() {
return this.surname ? `${this.name} ${this.surname}` : this.name;
}
get posts() {
return Post.where({ authorId: ... | unknown | unknown | [Advanced querying > Optimizing `id` queries]
constructor(data) {
super(data);
this.id = data.id;
this.name = data.name;
this.surname = data.surname;
this.email = data.email;
}
get fullName() {
return this.surname ? `${this.name} ${this.surname}` : this.name;
}
get posts() {
return Post.where({ authorId: ... | [Advanced querying > Optimizing `id` queries]
constructor(data) {
super(data);
this.id = data.id;
this.name = data.name;
this.surname = data.surname;
this.email = data.email;
}
get fullName() {
return this.surname ? `${this.name} ${this.surname}` : this.name;
}
get posts() {
return Post.where({ authorId: ... | code_snippets | ||
4f535909-19b9-4733-ab1b-39b91352f127 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 10 | SemanticChunker@1.0.0 | f34a1d04661ae109fa6174c761a987c13e17a8472fed55f48c7475054cba422c | [Model relationships > Multiple relationships]
> [!NOTE]
>
> I've carefully avoided **many-to-many relationships** here, mainly to keep things neat and simple. If you were to model them, you'd store an **array** of `id`s in a model instance, then use a `where` query to retrieve the related instances. The other side of... | unknown | unknown | [Model relationships > Multiple relationships]
> [!NOTE]
>
> I've carefully avoided **many-to-many relationships** here, mainly to keep things neat and simple. If you were to model them, you'd store an **array** of `id`s in a model instance, then use a `where` query to retrieve the related instances. The other side of... | [Model relationships > Multiple relationships]
> [!NOTE]
>
> I've carefully avoided **many-to-many relationships** here, mainly to keep things neat and simple. If you were to model them, you'd store an **array** of `id`s in a model instance, then use a `where` query to retrieve the related instances. The other side of... | code_snippets | ||
56c52e5e-b4a9-45ae-8363-47177eece54b | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 14 | SemanticChunker@1.0.0 | a1d8fbfb769ec2e2534e25cd9a539d2a28ef27efc34e31ef42ab37cab859eb59 | [Advanced querying > Optimizing `id` queries]
### Optimizing `id` queries
One thing you may have noticed is that we query records by `id` quite a lot. In fact, it may be our **most common operation**. We've already made record retrieval use a central storage on the `Model` class, but what if we could do more?
What I... | unknown | unknown | [Advanced querying > Optimizing `id` queries]
### Optimizing `id` queries
One thing you may have noticed is that we query records by `id` quite a lot. In fact, it may be our **most common operation**. We've already made record retrieval use a central storage on the `Model` class, but what if we could do more?
What I... | [Advanced querying > Optimizing `id` queries]
### Optimizing `id` queries
One thing you may have noticed is that we query records by `id` quite a lot. In fact, it may be our **most common operation**. We've already made record retrieval use a central storage on the `Model` class, but what if we could do more?
What I... | code_snippets | ||
59392cbd-d81c-46f9-862c-28aefdb8fbd7 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 5 | SemanticChunker@1.0.0 | 7263d4db178cb3cfeb5131c1f2192b99d938e420714170aee1561df1edc881df | [Data attributes > Temporal attributes]
#### Temporal attributes
Other cases may require comparison with external data or data that is **time-sensitive**. Let's look at our `Post` model for an example of a calculated attribute that depends on the current date. We'll first update its constructor to accept a `published... | unknown | unknown | [Data attributes > Temporal attributes]
#### Temporal attributes
Other cases may require comparison with external data or data that is **time-sensitive**. Let's look at our `Post` model for an example of a calculated attribute that depends on the current date. We'll first update its constructor to accept a `published... | [Data attributes > Temporal attributes]
#### Temporal attributes
Other cases may require comparison with external data or data that is **time-sensitive**. Let's look at our `Post` model for an example of a calculated attribute that depends on the current date. We'll first update its constructor to accept a `published... | code_snippets | ||
59f0b68e-42f9-4eba-8d91-95cf5204f4ee | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 7 | SemanticChunker@1.0.0 | fa92c5abdde2296b2eb4ade8f87ef7ae20c572ad5cde02f1477efdbb9a3ab296 | [Model relationships > Single relationships]
### Single relationships
Single relationships are simple to implement. In our case, we'll add a single relationship from the `Post` model to the `Author`, meaning that each post will have **exactly one** author.
To make single relationships easier, we'll use the `id` attr... | unknown | unknown | [Model relationships > Single relationships]
### Single relationships
Single relationships are simple to implement. In our case, we'll add a single relationship from the `Post` model to the `Author`, meaning that each post will have **exactly one** author.
To make single relationships easier, we'll use the `id` attr... | [Model relationships > Single relationships]
### Single relationships
Single relationships are simple to implement. In our case, we'll add a single relationship from the `Post` model to the `Author`, meaning that each post will have **exactly one** author.
To make single relationships easier, we'll use the `id` attr... | code_snippets | ||
5f016d7b-59d4-4c53-b011-8333db5d355d | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 16 | SemanticChunker@1.0.0 | e347d11f840b216f045e5e4d4edd8a8424efc5673f2c321d519f540d480da9d8 | [Advanced querying > Optimizing `id` queries]
```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')
... | unknown | unknown | [Advanced querying > Optimizing `id` queries]
```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')
... | [Advanced querying > Optimizing `id` queries]
```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')
... | code_snippets | ||
66d29538-68bc-4165-96cf-23097ed4dec8 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 8 | SemanticChunker@1.0.0 | 5e15e0c18dd5a8d92deded3bf05739f88bfd624c8125fb652fabc452a9ff4efb | [Single relationships > Related record retrieval]
#### Related record retrieval
Ok, now we have an `authorId` attribute in our `Post` model. But how do we get the actual `Author` model from this `authorId`? We can create a getter function in the `Post` model to do this, using our `find` method from before.
```js tit... | unknown | unknown | [Single relationships > Related record retrieval]
#### Related record retrieval
Ok, now we have an `authorId` attribute in our `Post` model. But how do we get the actual `Author` model from this `authorId`? We can create a getter function in the `Post` model to do this, using our `find` method from before.
```js tit... | [Single relationships > Related record retrieval]
#### Related record retrieval
Ok, now we have an `authorId` attribute in our `Post` model. But how do we get the actual `Author` model from this `authorId`? We can create a getter function in the `Post` model to do this, using our `find` method from before.
```js tit... | code_snippets | ||
6b617816-81b6-4db1-a72d-757cc61ddb3e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 11 | SemanticChunker@1.0.0 | 1143754bdc736bc519ae0c60d4d7a30f1d2dbcdd375cb20b07f07fdbbc08f1ed | [Directory structure > Advanced querying]
## Advanced querying
One emergent behavior of this implementation is the ability to **query models based on all their attributes**, not just the data attributes. This can unlock a lot of potential for complex queries and relationships. | unknown | unknown | [Directory structure > Advanced querying]
## Advanced querying
One emergent behavior of this implementation is the ability to **query models based on all their attributes**, not just the data attributes. This can unlock a lot of potential for complex queries and relationships. | [Directory structure > Advanced querying]
## Advanced querying
One emergent behavior of this implementation is the ability to **query models based on all their attributes**, not just the data attributes. This can unlock a lot of potential for complex queries and relationships. | code_snippets | ||
75e90b26-0f2d-44c7-ae93-4c83ae068293 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 13 | SemanticChunker@1.0.0 | 5f9e31e2a06211ab39e3e9a91623f247fca3a449c24811de5773064442934e55 | [Advanced querying > Querying relationships]
### Querying relationships
Relationships can be used in queries, too. After all, they're simply calculated properties we've given a special meaning to. This means we can query relationships just like any other attribute.
```js
const authors = Author.all;
authors.where(au... | unknown | unknown | [Advanced querying > Querying relationships]
### Querying relationships
Relationships can be used in queries, too. After all, they're simply calculated properties we've given a special meaning to. This means we can query relationships just like any other attribute.
```js
const authors = Author.all;
authors.where(au... | [Advanced querying > Querying relationships]
### Querying relationships
Relationships can be used in queries, too. After all, they're simply calculated properties we've given a special meaning to. This means we can query relationships just like any other attribute.
```js
const authors = Author.all;
authors.where(au... | code_snippets | ||
7ddd51d6-98e5-4048-b5b3-aa07ed1f4378 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 0 | SemanticChunker@1.0.0 | 9a3cae8f357cb491ebc0976a449cce70c7926987f5265e22309f55bb3c9ea7b0 | ---
title: Modeling complex JavaScript object attributes & relationships
shortTitle: Complex object attributes & relationships
language: javascript
tags: [object,class]
cover: digital-nomad-15
excerpt: Continuing on the journey to implement an ActiveRecord-like pattern in JavaScript with object attributes and relations... | unknown | unknown | ---
title: Modeling complex JavaScript object attributes & relationships
shortTitle: Complex object attributes & relationships
language: javascript
tags: [object,class]
cover: digital-nomad-15
excerpt: Continuing on the journey to implement an ActiveRecord-like pattern in JavaScript with object attributes and relations... | ---
title: Modeling complex JavaScript object attributes & relationships
shortTitle: Complex object attributes & relationships
language: javascript
tags: [object,class]
cover: digital-nomad-15
excerpt: Continuing on the journey to implement an ActiveRecord-like pattern in JavaScript with object attributes and relations... | code_snippets | ||
9dce33a5-b15a-411e-9f20-af9d0bd42822 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 1 | SemanticChunker@1.0.0 | 8f8c67b79d5f20c8f961998c69e8185d1aad1ab6f85b033d61db36682947e079 | [Directory structure]
## Directory structure
As mentioned previously, the directory structure for our project is fairly simple. This time, we'll be adding a **new model** in our `models` directory, along with some code in the existing `core` directory files. Here's what the new structure looks like:
```plaintext
src... | unknown | unknown | [Directory structure]
## Directory structure
As mentioned previously, the directory structure for our project is fairly simple. This time, we'll be adding a **new model** in our `models` directory, along with some code in the existing `core` directory files. Here's what the new structure looks like:
```plaintext
src... | [Directory structure]
## Directory structure
As mentioned previously, the directory structure for our project is fairly simple. This time, we'll be adding a **new model** in our `models` directory, along with some code in the existing `core` directory files. Here's what the new structure looks like:
```plaintext
src... | code_snippets | ||
9eb061af-aad2-4e8f-9297-003ac661c252 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 3 | SemanticChunker@1.0.0 | 8eb71b540519b21506a9901fd8ae17164806b945d5660dd544b64a2ac3c40a2f | [Model attributes > Data attributes]
### Data attributes
Implementing this in JavaScript isn't particularly hard, but we may want to consider - yet again - the often underused [JavaScript **getter** functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) to seamlessly access object... | unknown | unknown | [Model attributes > Data attributes]
### Data attributes
Implementing this in JavaScript isn't particularly hard, but we may want to consider - yet again - the often underused [JavaScript **getter** functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) to seamlessly access object... | [Model attributes > Data attributes]
### Data attributes
Implementing this in JavaScript isn't particularly hard, but we may want to consider - yet again - the often underused [JavaScript **getter** functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) to seamlessly access object... | code_snippets | ||
c1420dae-6df0-4c85-8939-13ff5fcadb67 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 6 | SemanticChunker@1.0.0 | 5f7f77dbf94484b0401dc21dd8bfe2451791f359aa06bfdf3ffbef2b2b904c7d | [Directory structure > Model relationships]
## Model relationships
In the ActiveRecord pattern, models can have relationships with other models. These relationships can be **one-to-one**, **one-to-many**, or **many-to-many**. One-to-one and one-to-many relationships are the most common and are relatively easy to impl... | unknown | unknown | [Directory structure > Model relationships]
## Model relationships
In the ActiveRecord pattern, models can have relationships with other models. These relationships can be **one-to-one**, **one-to-many**, or **many-to-many**. One-to-one and one-to-many relationships are the most common and are relatively easy to impl... | [Directory structure > Model relationships]
## Model relationships
In the ActiveRecord pattern, models can have relationships with other models. These relationships can be **one-to-one**, **one-to-many**, or **many-to-many**. One-to-one and one-to-many relationships are the most common and are relatively easy to impl... | code_snippets | ||
c2dde91e-035a-469a-b7d2-6ebd21a2ec69 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 4 | SemanticChunker@1.0.0 | 12f7ef0dc0cbcf6ff2b73e76d3fc776875e8bb9f8cb8900037a056c5e451462a | [Model attributes > Data attributes]
```
This simple model definition has given us access to the `id`, `name`, `surname`, and `email` attributes. We will call these _data attributes_ to differentiate them from _calculated attributes_, which we'll be defining next.
> [!NOTE]
>
> This is a semantics distinction rather... | unknown | unknown | [Model attributes > Data attributes]
```
This simple model definition has given us access to the `id`, `name`, `surname`, and `email` attributes. We will call these _data attributes_ to differentiate them from _calculated attributes_, which we'll be defining next.
> [!NOTE]
>
> This is a semantics distinction rather... | [Model attributes > Data attributes]
```
This simple model definition has given us access to the `id`, `name`, `surname`, and `email` attributes. We will call these _data attributes_ to differentiate them from _calculated attributes_, which we'll be defining next.
> [!NOTE]
>
> This is a semantics distinction rather... | code_snippets | ||
d9467cda-3db2-43a5-84ba-5af408b799c2 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-attributes-relationships.md | unknown | 93c09bd7-795a-4ce1-ba28-84c07a3c1623 | 15 | SemanticChunker@1.0.0 | 48309de01772449b4fd4f2b74a9081a25a8e105bc6c3529e923e9a9234ceb508 | [Advanced querying > Optimizing `id` queries]
```
This is a simple optimization that can greatly improve the performance of your application, especially if you're dealing with a large number of records.
> [!NOTE]
>
> In reality, in my project I didn't implement this _exactly_ like that. The main difference is that I... | unknown | unknown | [Advanced querying > Optimizing `id` queries]
```
This is a simple optimization that can greatly improve the performance of your application, especially if you're dealing with a large number of records.
> [!NOTE]
>
> In reality, in my project I didn't implement this _exactly_ like that. The main difference is that I... | [Advanced querying > Optimizing `id` queries]
```
This is a simple optimization that can greatly improve the performance of your application, especially if you're dealing with a large number of records.
> [!NOTE]
>
> In reality, in my project I didn't implement this _exactly_ like that. The main difference is that I... | code_snippets | ||
03a7042d-9eb2-4c4f-b029-47d4ff5c5c48 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 8 | SemanticChunker@1.0.0 | 2f832843b89f1686f4d2c88be165181f53f5b34172b21666b654756f14850cbd | [Typechecking primitives > Value is bigint]
### Value is bigint
BigInts are a relatively new addition to JavaScript. They are integers with arbitrary precision. BigInts are typechecked using `typeof`.
```js
const isBigInt = val => typeof val === 'bigint';
isBigInt(1n); // true
isBigInt(1); // false
``` | unknown | unknown | [Typechecking primitives > Value is bigint]
### Value is bigint
BigInts are a relatively new addition to JavaScript. They are integers with arbitrary precision. BigInts are typechecked using `typeof`.
```js
const isBigInt = val => typeof val === 'bigint';
isBigInt(1n); // true
isBigInt(1); // false
``` | [Typechecking primitives > Value is bigint]
### Value is bigint
BigInts are a relatively new addition to JavaScript. They are integers with arbitrary precision. BigInts are typechecked using `typeof`.
```js
const isBigInt = val => typeof val === 'bigint';
isBigInt(1n); // true
isBigInt(1); // false
``` | code_snippets | ||
0b4904ec-090f-497b-a6fb-e3db99b3158b | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 11 | SemanticChunker@1.0.0 | bfdbe0ac21c82192b848a2f12570a4129e6da8cb9d9ca7c212eceaae0c6fe166 | [Typechecking primitives > Value is primitive]
### Value is primitive
Checking if a value is of any primitive type is a bit more tricky. We can't simply use `typeof` for this, as it won't work for `null`.
Instead, we can **create an object** from the value and **compare** it with the value itself. If the value is pr... | unknown | unknown | [Typechecking primitives > Value is primitive]
### Value is primitive
Checking if a value is of any primitive type is a bit more tricky. We can't simply use `typeof` for this, as it won't work for `null`.
Instead, we can **create an object** from the value and **compare** it with the value itself. If the value is pr... | [Typechecking primitives > Value is primitive]
### Value is primitive
Checking if a value is of any primitive type is a bit more tricky. We can't simply use `typeof` for this, as it won't work for `null`.
Instead, we can **create an object** from the value and **compare** it with the value itself. If the value is pr... | code_snippets | ||
148a6972-c0f4-4bb3-a819-a27054b528cb | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 16 | SemanticChunker@1.0.0 | 3c204ba3ab2f7830c79c5b157fdd68a121262b85757ed1418a89efc69e060610 | [Value is plain object > Value is async function]
#### Value is async function
A function declared with the `async` keyword is considered asynchronous. Typechecking for async functions requires the use of `Object.prototype.toString()` and `Function.prototype.call()` to check if the result is `'[object AsyncFunction]'... | unknown | unknown | [Value is plain object > Value is async function]
#### Value is async function
A function declared with the `async` keyword is considered asynchronous. Typechecking for async functions requires the use of `Object.prototype.toString()` and `Function.prototype.call()` to check if the result is `'[object AsyncFunction]'... | [Value is plain object > Value is async function]
#### Value is async function
A function declared with the `async` keyword is considered asynchronous. Typechecking for async functions requires the use of `Object.prototype.toString()` and `Function.prototype.call()` to check if the result is `'[object AsyncFunction]'... | code_snippets | ||
2246bead-2107-4f19-a389-466deeb79f9e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 4 | SemanticChunker@1.0.0 | a61553dfce68eafb3f5ef89dd0f4e46c1a85fbc4f66aa94595bd6cc5e9a2c110 | [Typechecking primitives > Value is null]
### Value is null
Checking for a `null` value can only be done by comparing the value to `null` itself. This is because `typeof null` returns `'object'`, which is not what we want.
```js
const isNull = val => val === null;
isNull(null); // true
``` | unknown | unknown | [Typechecking primitives > Value is null]
### Value is null
Checking for a `null` value can only be done by comparing the value to `null` itself. This is because `typeof null` returns `'object'`, which is not what we want.
```js
const isNull = val => val === null;
isNull(null); // true
``` | [Typechecking primitives > Value is null]
### Value is null
Checking for a `null` value can only be done by comparing the value to `null` itself. This is because `typeof null` returns `'object'`, which is not what we want.
```js
const isNull = val => val === null;
isNull(null); // true
``` | code_snippets | ||
231c91aa-9153-421b-bcdd-297e37f90dcf | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 15 | SemanticChunker@1.0.0 | 203b76125e5907a2c3a0257a4b6d49754412a70ee0183673af8fbb1ea1bea9f8 | [Typechecking non-primitives > Value is plain object]
### Value is plain object
An object is considered **plain** when it is created by the `Object` constructor. This is in comparison to other objects like arrays, functions, or instances of classes, such as `Map`.
In order to check if a value is a plain object, we n... | unknown | unknown | [Typechecking non-primitives > Value is plain object]
### Value is plain object
An object is considered **plain** when it is created by the `Object` constructor. This is in comparison to other objects like arrays, functions, or instances of classes, such as `Map`.
In order to check if a value is a plain object, we n... | [Typechecking non-primitives > Value is plain object]
### Value is plain object
An object is considered **plain** when it is created by the `Object` constructor. This is in comparison to other objects like arrays, functions, or instances of classes, such as `Map`.
In order to check if a value is a plain object, we n... | code_snippets | ||
45342fc3-1373-444a-9b1a-2e74d2c2418a | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 2 | SemanticChunker@1.0.0 | 88553dc88c0aed9359d31c0a5d6585827c511e701910ac2a620b31d0d5a8abfa | [Value types > Typechecking primitives]
## Typechecking primitives
Primitives are generally easier to typecheck than objects and functions. This is because primitives are immutable, meaning that their values cannot be changed. Thus, we can simply compare the type of a value to the type we want to check for. This is w... | unknown | unknown | [Value types > Typechecking primitives]
## Typechecking primitives
Primitives are generally easier to typecheck than objects and functions. This is because primitives are immutable, meaning that their values cannot be changed. Thus, we can simply compare the type of a value to the type we want to check for. This is w... | [Value types > Typechecking primitives]
## Typechecking primitives
Primitives are generally easier to typecheck than objects and functions. This is because primitives are immutable, meaning that their values cannot be changed. Thus, we can simply compare the type of a value to the type we want to check for. This is w... | code_snippets | ||
4c86b841-e013-4b60-b3b8-c1d70de9fa69 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 10 | SemanticChunker@1.0.0 | acc9fdd0cfb9c2400c199a595557ba7ae8acb5e581049ea71e25cdb4389669f8 | [Typechecking primitives > Value is symbol]
### Value is symbol
Symbols are unique values that can be used as the key of an object property. They are also typechecked using `typeof`.
```js
const isSymbol = val => typeof val === 'symbol';
isSymbol(Symbol('x')); // true
isSymbol('x'); // false
``` | unknown | unknown | [Typechecking primitives > Value is symbol]
### Value is symbol
Symbols are unique values that can be used as the key of an object property. They are also typechecked using `typeof`.
```js
const isSymbol = val => typeof val === 'symbol';
isSymbol(Symbol('x')); // true
isSymbol('x'); // false
``` | [Typechecking primitives > Value is symbol]
### Value is symbol
Symbols are unique values that can be used as the key of an object property. They are also typechecked using `typeof`.
```js
const isSymbol = val => typeof val === 'symbol';
isSymbol(Symbol('x')); // true
isSymbol('x'); // false
``` | code_snippets | ||
610d6bbe-e64f-4dbc-82a8-5b85167824e1 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 17 | SemanticChunker@1.0.0 | 4fcfe45dd00819b65c38dabf0f9ad78969a25fde6f629354b1616e6cdbf54ea7 | [Value is plain object > Value is generator function]
#### Value is generator function
Generator functions can be typechecked in the same manner as async functions. The expected value for them is `'[object GeneratorFunction]'`.
```js
const isGeneratorFunction = val =>
Object.prototype.toString.call(val) === '[objec... | unknown | unknown | [Value is plain object > Value is generator function]
#### Value is generator function
Generator functions can be typechecked in the same manner as async functions. The expected value for them is `'[object GeneratorFunction]'`.
```js
const isGeneratorFunction = val =>
Object.prototype.toString.call(val) === '[objec... | [Value is plain object > Value is generator function]
#### Value is generator function
Generator functions can be typechecked in the same manner as async functions. The expected value for them is `'[object GeneratorFunction]'`.
```js
const isGeneratorFunction = val =>
Object.prototype.toString.call(val) === '[objec... | code_snippets | ||
71d368ce-14f2-4ae5-9529-990fdabc2fce | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 18 | SemanticChunker@1.0.0 | 4fafb9c1da5cbf56eab3384ad2803a720a658c0aabafb516864c6645e1cfeaad | [Typechecking non-primitives > Type of value]
### Type of value
If all else fails, or if you are working with classes and other custom types, you might want to get a string representation of the type of a value. This can be done using `Object.prototype.constructor` and `Function.prototype.name`.
```js
const getType ... | unknown | unknown | [Typechecking non-primitives > Type of value]
### Type of value
If all else fails, or if you are working with classes and other custom types, you might want to get a string representation of the type of a value. This can be done using `Object.prototype.constructor` and `Function.prototype.name`.
```js
const getType ... | [Typechecking non-primitives > Type of value]
### Type of value
If all else fails, or if you are working with classes and other custom types, you might want to get a string representation of the type of a value. This can be done using `Object.prototype.constructor` and `Function.prototype.name`.
```js
const getType ... | code_snippets | ||
7a332c56-56e4-4df8-b200-91b8e34901fc | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 0 | SemanticChunker@1.0.0 | 7c743f1860db4593f6c2f2f2ac34ace4e43c4c56877987665dd9e506692ceaa3 | ---
title: A complete guide to JavaScript typechecking
shortTitle: Typechecking guide
language: javascript
tags: [type]
cover: overgrown
excerpt: Learn all you need to know to effectively and efficiently typecheck values in JavaScript.
listed: true
dateModified: 2023-12-22
---
JavaScript's **dynamic typing** is one of... | unknown | unknown | ---
title: A complete guide to JavaScript typechecking
shortTitle: Typechecking guide
language: javascript
tags: [type]
cover: overgrown
excerpt: Learn all you need to know to effectively and efficiently typecheck values in JavaScript.
listed: true
dateModified: 2023-12-22
---
JavaScript's **dynamic typing** is one of... | ---
title: A complete guide to JavaScript typechecking
shortTitle: Typechecking guide
language: javascript
tags: [type]
cover: overgrown
excerpt: Learn all you need to know to effectively and efficiently typecheck values in JavaScript.
listed: true
dateModified: 2023-12-22
---
JavaScript's **dynamic typing** is one of... | code_snippets | ||
7ef89fc3-aed2-4663-9de2-e7cc8ab8f9cb | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 19 | SemanticChunker@1.0.0 | 66675dec753f34d6836ab018a49608d1faef8e3d7108e14390f63e62dea1f5bb | [Type of value > Check if value is of type]
#### Check if value is of type
Flipping the previous code snippet around, we can also check if a value is of a specific type. Same as before, special care needs to be taken for `undefined` and `null`, as the do not have a `constructor` property.
```js
const isOfType = (typ... | unknown | unknown | [Type of value > Check if value is of type]
#### Check if value is of type
Flipping the previous code snippet around, we can also check if a value is of a specific type. Same as before, special care needs to be taken for `undefined` and `null`, as the do not have a `constructor` property.
```js
const isOfType = (typ... | [Type of value > Check if value is of type]
#### Check if value is of type
Flipping the previous code snippet around, we can also check if a value is of a specific type. Same as before, special care needs to be taken for `undefined` and `null`, as the do not have a `constructor` property.
```js
const isOfType = (typ... | code_snippets | ||
8bd58fd3-216b-4486-978e-dfcadad81a71 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 3 | SemanticChunker@1.0.0 | aaa9dbb8dd947523b2eafbce92f70469e8e211c458c97864a14446524a9a68cf | [Typechecking primitives > Value is undefined]
### Value is undefined
Checking for an `undefined` value is as simple as comparing the value to `undefined`. This yields the exact same result as using the `typeof` operator.
```js
const isUndefined = val => val === undefined;
isUndefined(undefined); // true
``` | unknown | unknown | [Typechecking primitives > Value is undefined]
### Value is undefined
Checking for an `undefined` value is as simple as comparing the value to `undefined`. This yields the exact same result as using the `typeof` operator.
```js
const isUndefined = val => val === undefined;
isUndefined(undefined); // true
``` | [Typechecking primitives > Value is undefined]
### Value is undefined
Checking for an `undefined` value is as simple as comparing the value to `undefined`. This yields the exact same result as using the `typeof` operator.
```js
const isUndefined = val => val === undefined;
isUndefined(undefined); // true
``` | code_snippets | ||
90faba43-531c-44a5-9a04-21270fbd3d9f | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 14 | SemanticChunker@1.0.0 | 7bbd39f8099233094f2af98ed0f1150ceb010607a9603f5658d01a78d06807b4 | [Typechecking non-primitives > Value is function]
### Value is function
Luckily, functions are not as tricky as objects. We can simply use `typeof` to check if a value is a function.
```js
const isFunction = val => typeof val === 'function';
isFunction(x => x); // true
isFunction('x'); // false
```
> [!NOTE]
>
> *... | unknown | unknown | [Typechecking non-primitives > Value is function]
### Value is function
Luckily, functions are not as tricky as objects. We can simply use `typeof` to check if a value is a function.
```js
const isFunction = val => typeof val === 'function';
isFunction(x => x); // true
isFunction('x'); // false
```
> [!NOTE]
>
> *... | [Typechecking non-primitives > Value is function]
### Value is function
Luckily, functions are not as tricky as objects. We can simply use `typeof` to check if a value is a function.
```js
const isFunction = val => typeof val === 'function';
isFunction(x => x); // true
isFunction('x'); // false
```
> [!NOTE]
>
> *... | code_snippets | ||
a3756828-ca8c-4e6a-b80e-9045463d8ea6 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 7 | SemanticChunker@1.0.0 | affe5ac99b36ab2a0e61bc71dae6af4c2c994811f9decb4bdf97b59cdf3c25dd | [Typechecking primitives > Value is number]
### Value is number
Numbers can also be typechecked using `typeof`. However, this will also return `true` for `NaN`, which is a special numeric value that represents the result of an operation that cannot produce a normal result.
You can [read more about `NaN`](/js/s/value... | unknown | unknown | [Typechecking primitives > Value is number]
### Value is number
Numbers can also be typechecked using `typeof`. However, this will also return `true` for `NaN`, which is a special numeric value that represents the result of an operation that cannot produce a normal result.
You can [read more about `NaN`](/js/s/value... | [Typechecking primitives > Value is number]
### Value is number
Numbers can also be typechecked using `typeof`. However, this will also return `true` for `NaN`, which is a special numeric value that represents the result of an operation that cannot produce a normal result.
You can [read more about `NaN`](/js/s/value... | code_snippets | ||
b3bfafe9-afdc-4479-9aae-45a81f637b7e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 6 | SemanticChunker@1.0.0 | f2c21db1062255a800e31b073b99d3d7baf8306846a866d0b724c02db6d181b2 | [Typechecking primitives > Value is boolean]
### Value is boolean
Boolean values are either `true` or `false`. Checking for either value is relatively inefficient, so `typeof` is generally preferred.
```js
const isBoolean = val => typeof val === 'boolean';
isBoolean(true); // true
isBoolean(false); // true
isBoolea... | unknown | unknown | [Typechecking primitives > Value is boolean]
### Value is boolean
Boolean values are either `true` or `false`. Checking for either value is relatively inefficient, so `typeof` is generally preferred.
```js
const isBoolean = val => typeof val === 'boolean';
isBoolean(true); // true
isBoolean(false); // true
isBoolea... | [Typechecking primitives > Value is boolean]
### Value is boolean
Boolean values are either `true` or `false`. Checking for either value is relatively inefficient, so `typeof` is generally preferred.
```js
const isBoolean = val => typeof val === 'boolean';
isBoolean(true); // true
isBoolean(false); // true
isBoolea... | code_snippets | ||
b5c3770f-ed8a-457e-8545-d5b9d48d98f4 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 9 | SemanticChunker@1.0.0 | 59959d68b4591f20a91595721227e3fa32fee81830cad5feccd8bda3613dc053 | [Typechecking primitives > Value is string]
### Value is string
String primitives, like most other primitives, can be typechecked using `typeof`.
```js
const isString = val => typeof val === 'string';
isString('Hello!'); // true
isString(1); // false
``` | unknown | unknown | [Typechecking primitives > Value is string]
### Value is string
String primitives, like most other primitives, can be typechecked using `typeof`.
```js
const isString = val => typeof val === 'string';
isString('Hello!'); // true
isString(1); // false
``` | [Typechecking primitives > Value is string]
### Value is string
String primitives, like most other primitives, can be typechecked using `typeof`.
```js
const isString = val => typeof val === 'string';
isString('Hello!'); // true
isString(1); // false
``` | code_snippets | ||
cf5508d2-9b55-4b9c-843e-5f3070841e6e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 12 | SemanticChunker@1.0.0 | 8d69b18303fc042aeab3fada2d59585d4543656b5b1f55e79507ab5d8b9202d1 | [Value types > Typechecking non-primitives]
## Typechecking non-primitives
Objects and functions behave slightly differently than primitives. While `typeof` can get us part of the way there, we might want to employ some other methods, especially for objects. | unknown | unknown | [Value types > Typechecking non-primitives]
## Typechecking non-primitives
Objects and functions behave slightly differently than primitives. While `typeof` can get us part of the way there, we might want to employ some other methods, especially for objects. | [Value types > Typechecking non-primitives]
## Typechecking non-primitives
Objects and functions behave slightly differently than primitives. While `typeof` can get us part of the way there, we might want to employ some other methods, especially for objects. | code_snippets | ||
d1facaf8-b2e0-45d7-b40c-f40407a53374 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 5 | SemanticChunker@1.0.0 | da9c1189612c0007efd829e1a57447367e9c5adc5487b002b652281a3b952c58 | [Typechecking primitives > Value is nil]
### Value is nil
In some other languages, a value of `nil` is used to represent the absence of a value. In JavaScript, however, `null` and `undefined` are used for this purpose. Thus, checking for a `nil` value is the same as checking for a `null` or `undefined` value.
```js
... | unknown | unknown | [Typechecking primitives > Value is nil]
### Value is nil
In some other languages, a value of `nil` is used to represent the absence of a value. In JavaScript, however, `null` and `undefined` are used for this purpose. Thus, checking for a `nil` value is the same as checking for a `null` or `undefined` value.
```js
... | [Typechecking primitives > Value is nil]
### Value is nil
In some other languages, a value of `nil` is used to represent the absence of a value. In JavaScript, however, `null` and `undefined` are used for this purpose. Thus, checking for a `nil` value is the same as checking for a `null` or `undefined` value.
```js
... | code_snippets | ||
d71b9cf9-3185-4e94-95d2-1421fbfe36e4 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 1 | SemanticChunker@1.0.0 | 920138fded4727c54e0dd0cd60ba04f4154944709a33de4b39c1e5708c418a44 | [Value types]
## Value types
Before we dive into the different ways to typecheck values in JavaScript, let's take a look at the different **types of values** we can encounter in JavaScript.
| Type | Description | Example |
| ---- | ----------- | ------- |
| `undefined` | The value of a variable that has not been ass... | unknown | unknown | [Value types]
## Value types
Before we dive into the different ways to typecheck values in JavaScript, let's take a look at the different **types of values** we can encounter in JavaScript.
| Type | Description | Example |
| ---- | ----------- | ------- |
| `undefined` | The value of a variable that has not been ass... | [Value types]
## Value types
Before we dive into the different ways to typecheck values in JavaScript, let's take a look at the different **types of values** we can encounter in JavaScript.
| Type | Description | Example |
| ---- | ----------- | ------- |
| `undefined` | The value of a variable that has not been ass... | code_snippets | ||
e3371c99-d4b2-4023-9e13-bcabf7a4930e | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complete-guide-to-js-type-checking.md | unknown | 27150d2d-3948-49a2-88f0-c6957a306147 | 13 | SemanticChunker@1.0.0 | 259d8b06ce41e8f6adbee6ea6db8bbe5b705ffd6f1f9db76c96c613e572cda9c | [Typechecking non-primitives > Value is object]
### Value is object
As we've seen before `typeof` returns `'object'` for `null`. This is not what we want, when typechecking for objects. Instead, we can use the `Object` constructor to create an **object wrapper** for the given value. If the value is `null` or `undefin... | unknown | unknown | [Typechecking non-primitives > Value is object]
### Value is object
As we've seen before `typeof` returns `'object'` for `null`. This is not what we want, when typechecking for objects. Instead, we can use the `Object` constructor to create an **object wrapper** for the given value. If the value is `null` or `undefin... | [Typechecking non-primitives > Value is object]
### Value is object
As we've seen before `typeof` returns `'object'` for `null`. This is not what we want, when typechecking for objects. Instead, we can use the `Object` constructor to create an **object wrapper** for the given value. If the value is `null` or `undefin... | code_snippets | ||
06a6f152-ef89-45f2-8997-b712279cc971 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 7 | SemanticChunker@1.0.0 | 900f4dd049369291908e947fe7ecc96b947a92e0da952dd75c9787291952d1c3 | [Field validation > Emptiness constraints]
### Emptiness constraints
Having set up type-checking, we need to address the elephant in the room: `null`. We need to **allow some fields to be empty**, but we want to control this on the field definition level. This begs the question: _how?_
First off, we need to decide t... | unknown | unknown | [Field validation > Emptiness constraints]
### Emptiness constraints
Having set up type-checking, we need to address the elephant in the room: `null`. We need to **allow some fields to be empty**, but we want to control this on the field definition level. This begs the question: _how?_
First off, we need to decide t... | [Field validation > Emptiness constraints]
### Emptiness constraints
Having set up type-checking, we need to address the elephant in the room: `null`. We need to **allow some fields to be empty**, but we want to control this on the field definition level. This begs the question: _how?_
First off, we need to decide t... | code_snippets | ||
095e1c45-3816-4d1a-8e30-0a9668369955 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 2 | SemanticChunker@1.0.0 | 6979ffd8970df9a570acaf7e5e96c1988767f310755b3bceb7a21a0f494c0f61 | [Directory structure > Field validation]
## Field validation
I find the semantics of **relational databases** and **ActiveRecord** to be quite nice for dictating object structure, so I'll loosely base my implementation on them. Thus, fields can have **types**, decide whether they can be **empty** or not, and define a... | unknown | unknown | [Directory structure > Field validation]
## Field validation
I find the semantics of **relational databases** and **ActiveRecord** to be quite nice for dictating object structure, so I'll loosely base my implementation on them. Thus, fields can have **types**, decide whether they can be **empty** or not, and define a... | [Directory structure > Field validation]
## Field validation
I find the semantics of **relational databases** and **ActiveRecord** to be quite nice for dictating object structure, so I'll loosely base my implementation on them. Thus, fields can have **types**, decide whether they can be **empty** or not, and define a... | code_snippets | ||
1ca217c8-fb57-4a84-92d3-3533d71df025 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 19 | SemanticChunker@1.0.0 | 69105e185cf0060e118e9a6e1aee365e5bec175416495f60c2bebda9ea7e9cf4 | [Directory structure > Custom validators]
if (isAlias) {
if (typeof field[1] === 'string') fieldOptions.type = field[1];
else if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else
throw new Error(
`Invalid field definition for ${fieldName} in ${name}`
);
}
const { type: data... | unknown | unknown | [Directory structure > Custom validators]
if (isAlias) {
if (typeof field[1] === 'string') fieldOptions.type = field[1];
else if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else
throw new Error(
`Invalid field definition for ${fieldName} in ${name}`
);
}
const { type: data... | [Directory structure > Custom validators]
if (isAlias) {
if (typeof field[1] === 'string') fieldOptions.type = field[1];
else if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else
throw new Error(
`Invalid field definition for ${fieldName} in ${name}`
);
}
const { type: data... | code_snippets | ||
20e0755d-b0a7-4e53-a337-f6c66396b993 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 18 | SemanticChunker@1.0.0 | 2a8fdea735a9a073c12f9c220657e708331e0ea5e96d5c38620dd2cbae14c496 | [Directory structure > Custom validators]
## Custom validators
We've covered the basics of individual field validation, but what if we want to apply **custom validation conditions**? This is hard to cover by the current setup, however, it's possible to implement a model-wide custom validation system.
After tinkering... | unknown | unknown | [Directory structure > Custom validators]
## Custom validators
We've covered the basics of individual field validation, but what if we want to apply **custom validation conditions**? This is hard to cover by the current setup, however, it's possible to implement a model-wide custom validation system.
After tinkering... | [Directory structure > Custom validators]
## Custom validators
We've covered the basics of individual field validation, but what if we want to apply **custom validation conditions**? This is hard to cover by the current setup, however, it's possible to implement a model-wide custom validation system.
After tinkering... | code_snippets | ||
22d1cfe5-1b21-4875-a247-9299fdf9d458 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 28 | SemanticChunker@1.0.0 | 8829c4214f7867b24b2b72c33891fd416c3ba6d23a4b56b35505441342bee03f | [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', allowEmpty:... | 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', allowEmpty:... | [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', allowEmpty:... | code_snippets | ||
25aa8aae-3306-485e-b699-881c011414b4 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 14 | SemanticChunker@1.0.0 | 4fe5109d0184eb74a66e103e2584111ba0b7f0ff65b79aa5a3eec186a0bd604e | [Field uniqueness > Unique `id`]
```
Such a small change, yet it allows us to constrain the `id` field to be unique across all records of a model. Our `indexedInstances` storage is leveraged to check for uniqueness, taking advantage of the **performance** of the `Map` data structure. This will prevent us from creatin... | unknown | unknown | [Field uniqueness > Unique `id`]
```
Such a small change, yet it allows us to constrain the `id` field to be unique across all records of a model. Our `indexedInstances` storage is leveraged to check for uniqueness, taking advantage of the **performance** of the `Map` data structure. This will prevent us from creatin... | [Field uniqueness > Unique `id`]
```
Such a small change, yet it allows us to constrain the `id` field to be unique across all records of a model. Our `indexedInstances` storage is leveraged to check for uniqueness, taking advantage of the **performance** of the `Map` data structure. This will prevent us from creatin... | code_snippets | ||
2b3fb7c4-d8b4-4450-9dd5-a2ce0cccdfd7 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 26 | SemanticChunker@1.0.0 | 1c21cd7e2f30e6f18990d3143ddb19963e0def019a130889c2bb12469dbd343f | [Directory structure > Addendum: Code summary]
if (!attributeName) return;
const alias = isAlias ? attribute[1] : null;
serializer.serializableAttributes.push(attributeName);
Object.defineProperty(serializer.prototype, attributeName, {
get() {
if (!isAlias) return this.subject[attributeName];
if (typeof alias... | unknown | unknown | [Directory structure > Addendum: Code summary]
if (!attributeName) return;
const alias = isAlias ? attribute[1] : null;
serializer.serializableAttributes.push(attributeName);
Object.defineProperty(serializer.prototype, attributeName, {
get() {
if (!isAlias) return this.subject[attributeName];
if (typeof alias... | [Directory structure > Addendum: Code summary]
if (!attributeName) return;
const alias = isAlias ? attribute[1] : null;
serializer.serializableAttributes.push(attributeName);
Object.defineProperty(serializer.prototype, attributeName, {
get() {
if (!isAlias) return this.subject[attributeName];
if (typeof alias... | code_snippets | ||
3a968f6b-f908-4431-aac0-0880afe0751d | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 4 | SemanticChunker@1.0.0 | 34b0adf277a711e3027e005af6f7dd8f4bfa789919fa986b80cc521d38edb941 | [Field validation > Type constraints]
// Cache getters, using a WeakMap for each model/key pair
if (!Model.getterCache[name]) Model.getterCache[name] = {};
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = new Map();
}
model.fields = {};
['id', ...fields]... | unknown | unknown | [Field validation > Type constraints]
// Cache getters, using a WeakMap for each model/key pair
if (!Model.getterCache[name]) Model.getterCache[name] = {};
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = new Map();
}
model.fields = {};
['id', ...fields]... | [Field validation > Type constraints]
// Cache getters, using a WeakMap for each model/key pair
if (!Model.getterCache[name]) Model.getterCache[name] = {};
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = new Map();
}
model.fields = {};
['id', ...fields]... | code_snippets | ||
4e8d6e4b-a895-4d95-aa4f-92cf22f02818 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 17 | SemanticChunker@1.0.0 | 820bc91c66daff0c96baf4053a270f01e4296dd171a6d3c52e3942c2eb10d0e4 | [Field uniqueness > Optimizing indexed queries]
### Optimizing indexed queries
Our `find` method is perfect when querying records by their `id`. But, having multiple indices, we may as well add a `findBy` method to leverage these data structures. This will allow us to **query records by any field that has a unique co... | unknown | unknown | [Field uniqueness > Optimizing indexed queries]
### Optimizing indexed queries
Our `find` method is perfect when querying records by their `id`. But, having multiple indices, we may as well add a `findBy` method to leverage these data structures. This will allow us to **query records by any field that has a unique co... | [Field uniqueness > Optimizing indexed queries]
### Optimizing indexed queries
Our `find` method is perfect when querying records by their `id`. But, having multiple indices, we may as well add a `findBy` method to leverage these data structures. This will allow us to **query records by any field that has a unique co... | code_snippets | ||
5200642a-e3e2-40cc-be2f-d35530909363 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 0 | SemanticChunker@1.0.0 | 68ea3b5b8d4c0192185f2be9eb85af95f671e55750b6f7a10cb0ca239b25d4d6 | ---
title: Modeling complex JavaScript object field validation
shortTitle: Complex object field validation
language: javascript
tags: [object,class]
cover: planning
excerpt: Returning to the models and records part of the implementation, this time around we'll explore how to add constraints to individual fields.
listed... | unknown | unknown | ---
title: Modeling complex JavaScript object field validation
shortTitle: Complex object field validation
language: javascript
tags: [object,class]
cover: planning
excerpt: Returning to the models and records part of the implementation, this time around we'll explore how to add constraints to individual fields.
listed... | ---
title: Modeling complex JavaScript object field validation
shortTitle: Complex object field validation
language: javascript
tags: [object,class]
cover: planning
excerpt: Returning to the models and records part of the implementation, this time around we'll explore how to add constraints to individual fields.
listed... | code_snippets | ||
569c4acd-e3ce-4823-82a3-08a2de6ae265 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 20 | SemanticChunker@1.0.0 | bc158c43e8575b6e9ff72a9475972bb8526c9d7626cbd0f54eeda419e9558e1a | [Directory structure > Custom validators]
if (!fieldChecker(this[fieldName])) {
throw new Error(
`Invalid value for field ${fieldName} in ${modelName}: ${this[fieldName]}`
);
}
}
);
this.constructor.validations?.forEach(validation => {
if (!validation(this, Model.instances[modelName])) {
throw new Error(
`I... | unknown | unknown | [Directory structure > Custom validators]
if (!fieldChecker(this[fieldName])) {
throw new Error(
`Invalid value for field ${fieldName} in ${modelName}: ${this[fieldName]}`
);
}
}
);
this.constructor.validations?.forEach(validation => {
if (!validation(this, Model.instances[modelName])) {
throw new Error(
`I... | [Directory structure > Custom validators]
if (!fieldChecker(this[fieldName])) {
throw new Error(
`Invalid value for field ${fieldName} in ${modelName}: ${this[fieldName]}`
);
}
}
);
this.constructor.validations?.forEach(validation => {
if (!validation(this, Model.instances[modelName])) {
throw new Error(
`I... | code_snippets | ||
5cc63a0d-4698-4b3a-98ae-7385b335bf5f | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 25 | SemanticChunker@1.0.0 | 39bd969b1a94979de3af8ad75703c9fc10123e562947457350d433b4b753f98e | [Directory structure > Addendum: Code summary]
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
return Model.indexedInstances[this.name].id.get(id);
}
static findBy(fieldAndValue) {
const entries = Object.entries(fieldAndValue);
if (entries.lengt... | unknown | unknown | [Directory structure > Addendum: Code summary]
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
return Model.indexedInstances[this.name].id.get(id);
}
static findBy(fieldAndValue) {
const entries = Object.entries(fieldAndValue);
if (entries.lengt... | [Directory structure > Addendum: Code summary]
static scope(...scopes) {
return scopes.reduce((acc, scope) => this[scope](acc), this.all);
}
static find(id) {
return Model.indexedInstances[this.name].id.get(id);
}
static findBy(fieldAndValue) {
const entries = Object.entries(fieldAndValue);
if (entries.lengt... | code_snippets | ||
64562660-1d8b-49e3-b084-c922a9a7d9bb | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 13 | SemanticChunker@1.0.0 | 0764ab7b761c2103cc52d98877f9327b584ee58d8ab2b8df954bef2253eab387 | [Field uniqueness > Unique `id`]
let dataTypeChecker;
if (dataType === 'any') dataTypeChecker = value => value !== null;
else if (['string', 'boolean', 'number'].includes(dataType))
dataTypeChecker = value => typeof value === dataType;
else if (dataType === 'date')
dataTypeChecker = value => value instanceof Date... | unknown | unknown | [Field uniqueness > Unique `id`]
let dataTypeChecker;
if (dataType === 'any') dataTypeChecker = value => value !== null;
else if (['string', 'boolean', 'number'].includes(dataType))
dataTypeChecker = value => typeof value === dataType;
else if (dataType === 'date')
dataTypeChecker = value => value instanceof Date... | [Field uniqueness > Unique `id`]
let dataTypeChecker;
if (dataType === 'any') dataTypeChecker = value => value !== null;
else if (['string', 'boolean', 'number'].includes(dataType))
dataTypeChecker = value => typeof value === dataType;
else if (dataType === 'date')
dataTypeChecker = value => value instanceof Date... | code_snippets | ||
755b5a20-45c0-4794-a9fc-80cb89e0d4c6 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 16 | SemanticChunker@1.0.0 | 755ff4567bb75b763138994f72782833edfe28a1faa292d843c5decb686ba3bf | [Field uniqueness > Unique `id`]
```
That's it! Same performance and logic, more flexibility and we can add uniqueness constraints. Let's update our `Author` model to make sure the `email` field is unique.
```js title="src/models/author.js"
import Model from '#src/core/model.js';
export default class Author extends... | unknown | unknown | [Field uniqueness > Unique `id`]
```
That's it! Same performance and logic, more flexibility and we can add uniqueness constraints. Let's update our `Author` model to make sure the `email` field is unique.
```js title="src/models/author.js"
import Model from '#src/core/model.js';
export default class Author extends... | [Field uniqueness > Unique `id`]
```
That's it! Same performance and logic, more flexibility and we can add uniqueness constraints. Let's update our `Author` model to make sure the `email` field is unique.
```js title="src/models/author.js"
import Model from '#src/core/model.js';
export default class Author extends... | code_snippets | ||
758c3b74-0f67-4652-8072-98dbb3ae3654 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 8 | SemanticChunker@1.0.0 | 1943717e2d031e42b4b2487b95a4b5f2290135da2f7388ee258a5f8ef483e792 | [Field validation > Emptiness constraints]
if (isAlias) {
if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else fieldOptions.type = field[1];
}
const { type: dataType, allowEmpty } = fieldOptions;
let dataTypeChecker;
if (dataType === 'any') dataTypeChecker = value => value !... | unknown | unknown | [Field validation > Emptiness constraints]
if (isAlias) {
if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else fieldOptions.type = field[1];
}
const { type: dataType, allowEmpty } = fieldOptions;
let dataTypeChecker;
if (dataType === 'any') dataTypeChecker = value => value !... | [Field validation > Emptiness constraints]
if (isAlias) {
if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else fieldOptions.type = field[1];
}
const { type: dataType, allowEmpty } = fieldOptions;
let dataTypeChecker;
if (dataType === 'any') dataTypeChecker = value => value !... | code_snippets | ||
7ab37fb9-43e9-47b0-9793-35fcebc290e5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 24 | SemanticChunker@1.0.0 | bb36ec6317c30602c241f36e41ce6e15a2fd7702614efb19c6f7193633f537dc | [Directory structure > Addendum: Code summary]
Object.entries(Object.getOwnPropertyDescriptors(model.prototype)).forEach(
([key, descriptor]) => {
// Find getter functions, create the WeakMap, redefine the getter
if (typeof descriptor.get === 'function') {
Model.getterCache[name][key] = new WeakMap();
Object.defi... | unknown | unknown | [Directory structure > Addendum: Code summary]
Object.entries(Object.getOwnPropertyDescriptors(model.prototype)).forEach(
([key, descriptor]) => {
// Find getter functions, create the WeakMap, redefine the getter
if (typeof descriptor.get === 'function') {
Model.getterCache[name][key] = new WeakMap();
Object.defi... | [Directory structure > Addendum: Code summary]
Object.entries(Object.getOwnPropertyDescriptors(model.prototype)).forEach(
([key, descriptor]) => {
// Find getter functions, create the WeakMap, redefine the getter
if (typeof descriptor.get === 'function') {
Model.getterCache[name][key] = new WeakMap();
Object.defi... | code_snippets | ||
93b8745d-0e2f-4bc9-bb8a-b83c982497fd | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 10 | SemanticChunker@1.0.0 | dbd9f49b7559b84229481f184609cb9589d5276f39b5cfbefdea2b8bf84a0d8f | [Field validation > Emptiness constraints]
```
# [continued: part 1]
constructor(data) {
const modelName = this.constructor.name;
Object.entries(this.constructor.fields).forEach(
([fieldName, { fieldChecker }]) => {
this[fieldName] = data[fieldName] ?? defaultValue;
if (!fieldChecker(this[fieldName])) {
thro... | unknown | unknown | [Field validation > Emptiness constraints]
```
# [continued: part 1]
constructor(data) {
const modelName = this.constructor.name;
Object.entries(this.constructor.fields).forEach(
([fieldName, { fieldChecker }]) => {
this[fieldName] = data[fieldName] ?? defaultValue;
if (!fieldChecker(this[fieldName])) {
thro... | [Field validation > Emptiness constraints]
```
# [continued: part 1]
constructor(data) {
const modelName = this.constructor.name;
Object.entries(this.constructor.fields).forEach(
([fieldName, { fieldChecker }]) => {
this[fieldName] = data[fieldName] ?? defaultValue;
if (!fieldChecker(this[fieldName])) {
thro... | code_snippets | ||
962482de-6745-443b-bec1-247300279f87 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 27 | SemanticChunker@1.0.0 | e5210dc461a683043bd6bca005f753a339098435d0693b014b6bc15f3b922f3d | [Directory structure > Addendum: Code summary]
```
```js title="src/core/factory.js"
import Model from '#src/core/model.js';
const sequenceSymbol = Symbol('sequence');
const isSequence = value =>
value && typeof value[sequenceSymbol] === 'function';
export default class Factory {
static factoryMap = new Map();
... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/core/factory.js"
import Model from '#src/core/model.js';
const sequenceSymbol = Symbol('sequence');
const isSequence = value =>
value && typeof value[sequenceSymbol] === 'function';
export default class Factory {
static factoryMap = new Map();
... | [Directory structure > Addendum: Code summary]
```
```js title="src/core/factory.js"
import Model from '#src/core/model.js';
const sequenceSymbol = Symbol('sequence');
const isSequence = value =>
value && typeof value[sequenceSymbol] === 'function';
export default class Factory {
static factoryMap = new Map();
... | code_snippets | ||
9f408e2d-528e-4c6d-9c2c-f9f91f987546 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 6 | SemanticChunker@1.0.0 | e42ad7f0471f7f5afbaa5f2eab81d4a768e84bfaf2481b8070aa7c90a236a782 | [Field validation > Type constraints]
> [!TIP]
>
> If you're not familiar with the **nullish coalescing** (`??`) operator, I highly suggest reading up on the [previous article on the topic](/js/s/nullish-coalescing-optional-chaining/#nullish-coalescing). In this case, it's used instead of the logical OR (`||`) operato... | unknown | unknown | [Field validation > Type constraints]
> [!TIP]
>
> If you're not familiar with the **nullish coalescing** (`??`) operator, I highly suggest reading up on the [previous article on the topic](/js/s/nullish-coalescing-optional-chaining/#nullish-coalescing). In this case, it's used instead of the logical OR (`||`) operato... | [Field validation > Type constraints]
> [!TIP]
>
> If you're not familiar with the **nullish coalescing** (`??`) operator, I highly suggest reading up on the [previous article on the topic](/js/s/nullish-coalescing-optional-chaining/#nullish-coalescing). In this case, it's used instead of the logical OR (`||`) operato... | code_snippets | ||
9fe5226c-f60f-4e8d-ba2b-88ce485f240c | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 22 | SemanticChunker@1.0.0 | b8604aba90ac6debfca76a26e8c9598d2dc03a33270bfe29c2b0b6e3a9269f11 | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
The complete implementation is summarized below, as is traditional by now. This includes all the changes we've made to the `Model` class, as well as the changes to the `Author` and `Post` models, and all previous implementations.
You can also [... | unknown | unknown | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
The complete implementation is summarized below, as is traditional by now. This includes all the changes we've made to the `Model` class, as well as the changes to the `Author` and `Post` models, and all previous implementations.
You can also [... | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
The complete implementation is summarized below, as is traditional by now. This includes all the changes we've made to the `Model` class, as well as the changes to the `Author` and `Post` models, and all previous implementations.
You can also [... | code_snippets | ||
a83b3b04-1f2a-4673-b496-0fa6b72d11a3 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 23 | SemanticChunker@1.0.0 | a7b73a8b9f0d1471afcf1bd7d2b3974ccbfeef60e56a9f646d3eea95a9c2a946 | [Directory structure > Addendum: Code summary]
if (isAlias) {
if (typeof field[1] === 'string') fieldOptions.type = field[1];
else if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else
throw new Error(
`Invalid field definition for ${fieldName} in ${name}`
);
}
const { type:... | unknown | unknown | [Directory structure > Addendum: Code summary]
if (isAlias) {
if (typeof field[1] === 'string') fieldOptions.type = field[1];
else if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else
throw new Error(
`Invalid field definition for ${fieldName} in ${name}`
);
}
const { type:... | [Directory structure > Addendum: Code summary]
if (isAlias) {
if (typeof field[1] === 'string') fieldOptions.type = field[1];
else if (typeof field[1] === 'object')
fieldOptions = { ...fieldOptions, ...field[1] };
else
throw new Error(
`Invalid field definition for ${fieldName} in ${name}`
);
}
const { type:... | code_snippets | ||
a9aaad62-4c4d-4906-901c-efb946ba8292 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 11 | SemanticChunker@1.0.0 | 1cc6d7c00f1ab42625f58e06260fea0a7fe3e246fcdf27ace6075f7dc941e339 | [Directory structure > Field uniqueness]
## Field uniqueness
A more complex constraint that is often required is **field uniqueness**. This is especially useful for fields like `id`, which should be unique across all records of a model. This also opens up the potential for **multiple indices** on a model, which can b... | unknown | unknown | [Directory structure > Field uniqueness]
## Field uniqueness
A more complex constraint that is often required is **field uniqueness**. This is especially useful for fields like `id`, which should be unique across all records of a model. This also opens up the potential for **multiple indices** on a model, which can b... | [Directory structure > Field uniqueness]
## Field uniqueness
A more complex constraint that is often required is **field uniqueness**. This is especially useful for fields like `id`, which should be unique across all records of a model. This also opens up the potential for **multiple indices** on a model, which can b... | code_snippets | ||
d2514232-b6c1-4fa2-92df-c2c03ef8341a | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 5 | SemanticChunker@1.0.0 | f7d56ed9342c0cc57f76ed495b7d05f559a9b476aeac2d84cf6b97aef8296d2a | [Field validation > Type constraints]
```
> [!NOTE]
>
> Some **design decisions** in this code snippet will come to make sense in the next couple of sections, as we add more constraints to our fields. If they feel overengineered at this point, it's because I stripped down the final implementation to its individual st... | unknown | unknown | [Field validation > Type constraints]
```
> [!NOTE]
>
> Some **design decisions** in this code snippet will come to make sense in the next couple of sections, as we add more constraints to our fields. If they feel overengineered at this point, it's because I stripped down the final implementation to its individual st... | [Field validation > Type constraints]
```
> [!NOTE]
>
> Some **design decisions** in this code snippet will come to make sense in the next couple of sections, as we add more constraints to our fields. If they feel overengineered at this point, it's because I stripped down the final implementation to its individual st... | code_snippets | ||
d2aa245d-5ae1-455a-92d5-b75f760d15b9 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 3 | SemanticChunker@1.0.0 | b410a9fcf88aee4adc43d96ea88f14b3edd88ca0d3d6954a9c25747525cca6d5 | [Field validation > Type constraints]
### Type constraints
Relational databases have a small subset of **data types** that you can use. Instead of going down their specific implementation route, we'll adapt this concept to JavaScript. What we want is to be able to define a fields as a `string`, `number`, `boolean`, o... | unknown | unknown | [Field validation > Type constraints]
### Type constraints
Relational databases have a small subset of **data types** that you can use. Instead of going down their specific implementation route, we'll adapt this concept to JavaScript. What we want is to be able to define a fields as a `string`, `number`, `boolean`, o... | [Field validation > Type constraints]
### Type constraints
Relational databases have a small subset of **data types** that you can use. Instead of going down their specific implementation route, we'll adapt this concept to JavaScript. What we want is to be able to define a fields as a `string`, `number`, `boolean`, o... | code_snippets | ||
d9b81f5f-c9ea-4df3-8a62-ccb265dacb3c | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 29 | SemanticChunker@1.0.0 | ae56b3488f1c6854015addacb4df5fea7240026a07fc6ca68d1e801724a90181 | [Directory structure > Addendum: Code summary]
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 | [Directory structure > Addendum: Code summary]
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',
... | [Directory structure > Addendum: Code summary]
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 | ||
dcf97306-b943-4aaf-afe6-a774cfa3cce2 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 1 | SemanticChunker@1.0.0 | dd5e35a968eea3e9391936a72334dab279d01c54dfa7bcee6ceb3ac0211f43b8 | [Directory structure]
## Directory structure
This time around, **we won't be making any changes to the existing directory structure**. We'll only make some changes to our `Model` class and update individual `models` to include field validation.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ ├── seri... | unknown | unknown | [Directory structure]
## Directory structure
This time around, **we won't be making any changes to the existing directory structure**. We'll only make some changes to our `Model` class and update individual `models` to include field validation.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ ├── seri... | [Directory structure]
## Directory structure
This time around, **we won't be making any changes to the existing directory structure**. We'll only make some changes to our `Model` class and update individual `models` to include field validation.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ ├── seri... | code_snippets | ||
e1d048fa-35fe-45c5-a9e1-8a8cd50aec89 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 12 | SemanticChunker@1.0.0 | 18ee49d132641a3c9ad435f2e8756d800262d1aa3988ac4a674b73e72eede479 | [Field uniqueness > Unique `id`]
### Unique `id`
We'll start by constraining the `id` field to ensure that it's **unique across all records of a model**. This needs yet another small change in the `prepare` method of our `Model`.
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
export... | unknown | unknown | [Field uniqueness > Unique `id`]
### Unique `id`
We'll start by constraining the `id` field to ensure that it's **unique across all records of a model**. This needs yet another small change in the `prepare` method of our `Model`.
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
export... | [Field uniqueness > Unique `id`]
### Unique `id`
We'll start by constraining the `id` field to ensure that it's **unique across all records of a model**. This needs yet another small change in the `prepare` method of our `Model`.
```js title="src/core/model.js"
import RecordSet from '#src/core/recordSet.js';
export... | code_snippets | ||
e3459bdb-5738-466b-9d84-2d5609e68cf5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 9 | SemanticChunker@1.0.0 | 3af27f68b1359b9845b198a73a116ae26bd5305bacc6c4ffa8ec93b9fab6489c | [Field validation > Emptiness constraints]
```
### Default values
Thus far, we've worked under the assumption of `null` being the empty value. However, we may want to **default to a different value**. This is especially useful for fields that are not allowed to be empty, but we still want to have a default value.
S... | unknown | unknown | [Field validation > Emptiness constraints]
```
### Default values
Thus far, we've worked under the assumption of `null` being the empty value. However, we may want to **default to a different value**. This is especially useful for fields that are not allowed to be empty, but we still want to have a default value.
S... | [Field validation > Emptiness constraints]
```
### Default values
Thus far, we've worked under the assumption of `null` being the empty value. However, we may want to **default to a different value**. This is especially useful for fields that are not allowed to be empty, but we still want to have a default value.
S... | code_snippets | ||
e3db5e54-22f6-4e0f-a42f-795324f1a757 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 21 | SemanticChunker@1.0.0 | c058fa16b9bbac8188795c52c8c8028d14748bb1f1606da9931da862541b5eef | [Directory structure > Conclusion]
## Conclusion
That's a wrap! Our models can finally be used to store structured data. We've covered **type** constraints, **emptiness** constraints, **default values**, field **uniqueness**, and **custom validators**. This is a great starting point for a more complex system, which c... | unknown | unknown | [Directory structure > Conclusion]
## Conclusion
That's a wrap! Our models can finally be used to store structured data. We've covered **type** constraints, **emptiness** constraints, **default values**, field **uniqueness**, and **custom validators**. This is a great starting point for a more complex system, which c... | [Directory structure > Conclusion]
## Conclusion
That's a wrap! Our models can finally be used to store structured data. We've covered **type** constraints, **emptiness** constraints, **default values**, field **uniqueness**, and **custom validators**. This is a great starting point for a more complex system, which c... | code_snippets | ||
ee93472c-759d-4abb-9c8a-1c5c65f436f5 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 30 | SemanticChunker@1.0.0 | 7e8470dcfb611b3e29a41b7c3117929e982db7a5a7c25d6d29ff254a36800922 | [Directory structure > Addendum: Code summary]
```
```js title="spec/factories/postFactory.js"
import Factory from '#src/core/factory.js';
import Post from '#src/models/post.js';
const idSequence = Factory.sequence();
const titleSequence = Factory.sequence(n => `Post #${n}`);
const base = {
id: idSequence,
title:... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="spec/factories/postFactory.js"
import Factory from '#src/core/factory.js';
import Post from '#src/models/post.js';
const idSequence = Factory.sequence();
const titleSequence = Factory.sequence(n => `Post #${n}`);
const base = {
id: idSequence,
title:... | [Directory structure > Addendum: Code summary]
```
```js title="spec/factories/postFactory.js"
import Factory from '#src/core/factory.js';
import Post from '#src/models/post.js';
const idSequence = Factory.sequence();
const titleSequence = Factory.sequence(n => `Post #${n}`);
const base = {
id: idSequence,
title:... | code_snippets | ||
f4b403b4-3deb-4002-8a46-1e0158b1b890 | unknown | file:///home/sanjeev/Downloads/depthapi/datasets/30-seconds-of-code/content/snippets/js/s/complex-object-field-validation.md | unknown | 291af9dc-2d1a-4f6e-8704-aea55a679d09 | 15 | SemanticChunker@1.0.0 | c2a5efe2b20c7afb44db05436393f6d315af823d8813b8b595fab1e09fc28e5e | [Field uniqueness > Unique `id`]
```
# [continued: part 1]
fieldChecker = value => fieldTypeChecker(value) && uniqueChecker(value);
}
model.fields[fieldName] = { fieldChecker, defaultValue };
});
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = model.ind... | unknown | unknown | [Field uniqueness > Unique `id`]
```
# [continued: part 1]
fieldChecker = value => fieldTypeChecker(value) && uniqueChecker(value);
}
model.fields[fieldName] = { fieldChecker, defaultValue };
});
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = model.ind... | [Field uniqueness > Unique `id`]
```
# [continued: part 1]
fieldChecker = value => fieldTypeChecker(value) && uniqueChecker(value);
}
model.fields[fieldName] = { fieldChecker, defaultValue };
});
// Create a map to speed up queries
if (!Model.indexedInstances[name]) {
Model.indexedInstances[name] = model.ind... | code_snippets | ||
10b539f2-368c-47e6-85b1-001820a9c1fa | 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 | 16 | SemanticChunker@1.0.0 | 98f386dc04a8c4b7ef44daab2206919fa87ba153f933692eca30b4cdb02e388e | [Sequences > Sequence setup]
const idSequence = Factory.sequence();
const base = {
id: idSequence,
name: 'Author',
surname: 'Authorson',
email: 'author@authornet.io',
};
export default class AuthorFactory extends Factory {
static {
super.prepare(this, Author, base);
}
}
```
With these changes in place, we c... | unknown | unknown | [Sequences > Sequence setup]
const idSequence = Factory.sequence();
const base = {
id: idSequence,
name: 'Author',
surname: 'Authorson',
email: 'author@authornet.io',
};
export default class AuthorFactory extends Factory {
static {
super.prepare(this, Author, base);
}
}
```
With these changes in place, we c... | [Sequences > Sequence setup]
const idSequence = Factory.sequence();
const base = {
id: idSequence,
name: 'Author',
surname: 'Authorson',
email: 'author@authornet.io',
};
export default class AuthorFactory extends Factory {
static {
super.prepare(this, Author, base);
}
}
```
With these changes in place, we c... | code_snippets | ||
14da2fe0-926a-4a72-b89b-c2f1ba256ac8 | 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 | 20 | SemanticChunker@1.0.0 | ea6313d9b7bd801c832ec0a23fc83c72eba7e82201f024dd2934b8984cede591 | [Directory structure > Addendum: Code summary]
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const attributeName = isAlias ? attribute[0] : attribute;
if (!attributeName) return;
const alias = isAlias ? attribute[1] : null;
serializer.serializableAttributes.push(attr... | unknown | unknown | [Directory structure > Addendum: Code summary]
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const attributeName = isAlias ? attribute[0] : attribute;
if (!attributeName) return;
const alias = isAlias ? attribute[1] : null;
serializer.serializableAttributes.push(attr... | [Directory structure > Addendum: Code summary]
serializableAttributes.forEach((attribute) => {
const isAlias = Array.isArray(attribute);
const attributeName = isAlias ? attribute[0] : attribute;
if (!attributeName) return;
const alias = isAlias ? attribute[1] : null;
serializer.serializableAttributes.push(attr... | code_snippets | ||
2edb1e30-5c04-4656-9095-c4687a0cf914 | 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 | 14 | SemanticChunker@1.0.0 | 85a13c1ba9324ce32d00fcb77fe98f324c96e563b2c1bc32c743ce2639c425ba | [Sequences > Sequence setup]
A simple **closure** does the trick here. We'll allow the caller to pass a function to transform the sequence value, and we'll return an object with a `[sequenceSymbol]` key that contains the sequence function. This way, we can easily look up the sequence function in the `prepare` method, ... | unknown | unknown | [Sequences > Sequence setup]
A simple **closure** does the trick here. We'll allow the caller to pass a function to transform the sequence value, and we'll return an object with a `[sequenceSymbol]` key that contains the sequence function. This way, we can easily look up the sequence function in the `prepare` method, ... | [Sequences > Sequence setup]
A simple **closure** does the trick here. We'll allow the caller to pass a function to transform the sequence value, and we'll return an object with a `[sequenceSymbol]` key that contains the sequence function. This way, we can easily look up the sequence function in the `prepare` method, ... | code_snippets | ||
424f552e-926d-4535-ac4f-0493f1e8db1e | 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 | 13 | SemanticChunker@1.0.0 | a6d6dab30631805307d26e3bc07c3a9f03b5adb9ca1c09a04c0b5785afbfee46 | [Sequences > Sequence setup]
### Sequence setup
Ok, we're going in the deep end now. We need a way to easily define a sequence inside a factory subclass and assign it to the base data. The sequence must generate a **new value each time**, yet it must be passed into the `base` definition. This is a bit tricky, but we ... | unknown | unknown | [Sequences > Sequence setup]
### Sequence setup
Ok, we're going in the deep end now. We need a way to easily define a sequence inside a factory subclass and assign it to the base data. The sequence must generate a **new value each time**, yet it must be passed into the `base` definition. This is a bit tricky, but we ... | [Sequences > Sequence setup]
### Sequence setup
Ok, we're going in the deep end now. We need a way to easily define a sequence inside a factory subclass and assign it to the base data. The sequence must generate a **new value each time**, yet it must be passed into the `base` definition. This is a bit tricky, but we ... | code_snippets | ||
4ac445b0-4390-454e-847a-b2101f67ca4e | 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 | 0 | SemanticChunker@1.0.0 | 1325d3bd4088c161b35625eaf78fde4121013d57a6d682b2e29e8e14bdd2ba47 | ---
title: Modeling complex JavaScript object factories
shortTitle: Complex object factories
language: javascript
tags: [object,class]
cover: tranquil-desktop
excerpt: Expanding even further upon our ActiveRecord-inspired project, we'll figure out how to create factories that produce complex objects.
listed: true
dateM... | unknown | unknown | ---
title: Modeling complex JavaScript object factories
shortTitle: Complex object factories
language: javascript
tags: [object,class]
cover: tranquil-desktop
excerpt: Expanding even further upon our ActiveRecord-inspired project, we'll figure out how to create factories that produce complex objects.
listed: true
dateM... | ---
title: Modeling complex JavaScript object factories
shortTitle: Complex object factories
language: javascript
tags: [object,class]
cover: tranquil-desktop
excerpt: Expanding even further upon our ActiveRecord-inspired project, we'll figure out how to create factories that produce complex objects.
listed: true
dateM... | code_snippets | ||
4e1073e2-be56-42d3-ae5b-3a4f40ae54eb | 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 | 5 | SemanticChunker@1.0.0 | bf16f83a6b707b269259ce2aaadaab34ec85bbb4c5d0f9f4689575d67cc59eac | [The Factory class > Preparing the factory]
```
> [!NOTE]
>
> In some cases, you may want **customizable traits** with parameters. For example, you might want a few interdependent fields combined in a trait, but you may want to pass some parameter to create them. While this isn't exactly covered in this article, the ... | unknown | unknown | [The Factory class > Preparing the factory]
```
> [!NOTE]
>
> In some cases, you may want **customizable traits** with parameters. For example, you might want a few interdependent fields combined in a trait, but you may want to pass some parameter to create them. While this isn't exactly covered in this article, the ... | [The Factory class > Preparing the factory]
```
> [!NOTE]
>
> In some cases, you may want **customizable traits** with parameters. For example, you might want a few interdependent fields combined in a trait, but you may want to pass some parameter to create them. While this isn't exactly covered in this article, the ... | code_snippets | ||
4e25e714-2979-40ff-b84f-85825ce90a4f | 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 | 9 | SemanticChunker@1.0.0 | 1ccfe2a6615622f61f57ad10d88f7eafba7bc81bd806d3892c8d2b4ef1688cc1 | [The Factory class > Clearing objects]
### Clearing objects
In some cases, we might want to **clear out objects**, to make sure they don't interfere with our tests. This is especially useful when we're counting records or checking relationships, for example.
We can add two new methods, `clear` and `clearAll`, to our... | unknown | unknown | [The Factory class > Clearing objects]
### Clearing objects
In some cases, we might want to **clear out objects**, to make sure they don't interfere with our tests. This is especially useful when we're counting records or checking relationships, for example.
We can add two new methods, `clear` and `clearAll`, to our... | [The Factory class > Clearing objects]
### Clearing objects
In some cases, we might want to **clear out objects**, to make sure they don't interfere with our tests. This is especially useful when we're counting records or checking relationships, for example.
We can add two new methods, `clear` and `clearAll`, to our... | code_snippets | ||
4e96b2ec-2d5e-4aa2-abb5-cc470ebc1d4c | 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 | 15 | SemanticChunker@1.0.0 | 4f4311eaba20a1e0b74229c50e15e809b85ccbf430ba05105e1874d0be4b5988 | [Sequences > Sequence setup]
```
That looks fairly complex at this point. Let's unpack the changes we've made. Using the `isSequence` helper function, we can check if a key in the `base` is a sequence. In that case, we'll use the function returned by the sequence to generate the value. Otherwise, we'll use the value ... | unknown | unknown | [Sequences > Sequence setup]
```
That looks fairly complex at this point. Let's unpack the changes we've made. Using the `isSequence` helper function, we can check if a key in the `base` is a sequence. In that case, we'll use the function returned by the sequence to generate the value. Otherwise, we'll use the value ... | [Sequences > Sequence setup]
```
That looks fairly complex at this point. Let's unpack the changes we've made. Using the `isSequence` helper function, we can check if a key in the `base` is a sequence. In that case, we'll use the function returned by the sequence to generate the value. Otherwise, we'll use the value ... | code_snippets | ||
66d59f37-982e-405a-9ff6-17541ec9af4a | 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 | 6 | SemanticChunker@1.0.0 | 5a5844b0aee1153bb809ed087aa84dcac7942beb088ddcad4070a4ad4f22c117 | [The Factory class > Preparing the factory]
```
Notice how we're using the `prepare` method to set up our factories. We're passing the factory itself, the model it's supposed to create, the base data for the model, and any traits we want to apply to the base data. As `Author` is a little simpler for the time being, w... | unknown | unknown | [The Factory class > Preparing the factory]
```
Notice how we're using the `prepare` method to set up our factories. We're passing the factory itself, the model it's supposed to create, the base data for the model, and any traits we want to apply to the base data. As `Author` is a little simpler for the time being, w... | [The Factory class > Preparing the factory]
```
Notice how we're using the `prepare` method to set up our factories. We're passing the factory itself, the model it's supposed to create, the base data for the model, and any traits we want to apply to the base data. As `Author` is a little simpler for the time being, w... | code_snippets | ||
721def5e-1000-4ed7-ad79-94bc1feff78f | 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 | 4 | SemanticChunker@1.0.0 | a1156af333853340befec87fcf9592db6f668c1f13fc0c83c1e48074c2fd9c31 | [The Factory class > Preparing the factory]
### Preparing the factory
First off, we will follow the by-now familiar pattern of using [**static initialization blocks**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks) to create a **registry** of factories. This wi... | unknown | unknown | [The Factory class > Preparing the factory]
### Preparing the factory
First off, we will follow the by-now familiar pattern of using [**static initialization blocks**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks) to create a **registry** of factories. This wi... | [The Factory class > Preparing the factory]
### Preparing the factory
First off, we will follow the by-now familiar pattern of using [**static initialization blocks**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Static_initialization_blocks) to create a **registry** of factories. This wi... | code_snippets | ||
78750ffd-9052-4bcc-8d6f-76c0bb7c54de | 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 | 19 | SemanticChunker@1.0.0 | b04ed0d0fd8e134fd8ad21a2265ded3db21ca3f93840c5668fa1853d15762102 | [Directory structure > Addendum: Code summary]
// Store the instance in the instances and indexedInstances
Model.instances[modelName].push(this);
Model.indexedInstances[modelName].set(data.id, this);
}
static get all() {
return RecordSet.from(Model.instances[this.name] || []);
}
static where(query) {
return ... | unknown | unknown | [Directory structure > Addendum: Code summary]
// Store the instance in the instances and indexedInstances
Model.instances[modelName].push(this);
Model.indexedInstances[modelName].set(data.id, this);
}
static get all() {
return RecordSet.from(Model.instances[this.name] || []);
}
static where(query) {
return ... | [Directory structure > Addendum: Code summary]
// Store the instance in the instances and indexedInstances
Model.instances[modelName].push(this);
Model.indexedInstances[modelName].set(data.id, this);
}
static get all() {
return RecordSet.from(Model.instances[this.name] || []);
}
static where(query) {
return ... | code_snippets | ||
86382917-4fc2-4705-9b40-55db765539e1 | 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 | 3 | SemanticChunker@1.0.0 | a7a49511616943dfde1186354a0ebbd6ee6369e450ffd1225453f3e521e4ba23 | [Directory structure > The Factory class]
## The Factory class
To create our factories, we'll start by creating a `Factory` class in the `core` directory. As we usually do, we'll start simple and build from there. | unknown | unknown | [Directory structure > The Factory class]
## The Factory class
To create our factories, we'll start by creating a `Factory` class in the `core` directory. As we usually do, we'll start simple and build from there. | [Directory structure > The Factory class]
## The Factory class
To create our factories, we'll start by creating a `Factory` class in the `core` directory. As we usually do, we'll start simple and build from there. | code_snippets | ||
87ff8ecb-f01d-4bfc-a524-15f326507a75 | 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 | 1 | SemanticChunker@1.0.0 | 9dd05a5445226692da842537dfc24a47c5f1ab16d4ea51a28fcf8511caca64bc | [Directory structure]
## Directory structure
On top of what we previously built, we'll add a **new class** in the `core` directory, called `Factory`. We'll also start populating the `spec` directory with `factories` for our models.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ ├── serializer.js
│ └... | unknown | unknown | [Directory structure]
## Directory structure
On top of what we previously built, we'll add a **new class** in the `core` directory, called `Factory`. We'll also start populating the `spec` directory with `factories` for our models.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ ├── serializer.js
│ └... | [Directory structure]
## Directory structure
On top of what we previously built, we'll add a **new class** in the `core` directory, called `Factory`. We'll also start populating the `spec` directory with `factories` for our models.
```plaintext
src/
├── core/
│ ├── model.js
│ ├── recordSet.js
│ ├── serializer.js
│ └... | code_snippets | ||
99f4ef68-e06e-4cbe-b7e4-7af0c77281ec | 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 | 11 | SemanticChunker@1.0.0 | 082095d47e3026f5ff9f06bc6425e9ca74320815b3ad9f9b449f225fc3adc1ef | [The Factory class > Convenience methods]
```
So far, we've ended up exactly where we were before. Only difference is that we've moved the `build` method to the factory subclass, using `Object.defineProperty()`, which allows us to define a property on the factory subclass. Notice how we can use the `factory` variable... | unknown | unknown | [The Factory class > Convenience methods]
```
So far, we've ended up exactly where we were before. Only difference is that we've moved the `build` method to the factory subclass, using `Object.defineProperty()`, which allows us to define a property on the factory subclass. Notice how we can use the `factory` variable... | [The Factory class > Convenience methods]
```
So far, we've ended up exactly where we were before. Only difference is that we've moved the `build` method to the factory subclass, using `Object.defineProperty()`, which allows us to define a property on the factory subclass. Notice how we can use the `factory` variable... | code_snippets | ||
9e7dc958-7ec3-4665-b5f1-7698cefb8055 | 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 | 7 | SemanticChunker@1.0.0 | e8dfc51b1fa80270868a74c2c771ebcece0ed89fffd7589d7412f15315f66cfd | [The Factory class > Customizing objects]
### Customizing objects
Our traits are nice and all, but it's inefficient to have to define a trait for every special case in our codebase. While they provide the benefit of **composition**, they can still end up becoming a bit unwieldy.
To solve this, we can allow the `buil... | unknown | unknown | [The Factory class > Customizing objects]
### Customizing objects
Our traits are nice and all, but it's inefficient to have to define a trait for every special case in our codebase. While they provide the benefit of **composition**, they can still end up becoming a bit unwieldy.
To solve this, we can allow the `buil... | [The Factory class > Customizing objects]
### Customizing objects
Our traits are nice and all, but it's inefficient to have to define a trait for every special case in our codebase. While they provide the benefit of **composition**, they can still end up becoming a bit unwieldy.
To solve this, we can allow the `buil... | code_snippets | ||
a012107f-0530-4e38-93d9-5056b7c70571 | 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 | 21 | SemanticChunker@1.0.0 | e5210dc461a683043bd6bca005f753a339098435d0693b014b6bc15f3b922f3d | [Directory structure > Addendum: Code summary]
```
```js title="src/core/factory.js"
import Model from '#src/core/model.js';
const sequenceSymbol = Symbol('sequence');
const isSequence = value =>
value && typeof value[sequenceSymbol] === 'function';
export default class Factory {
static factoryMap = new Map();
... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="src/core/factory.js"
import Model from '#src/core/model.js';
const sequenceSymbol = Symbol('sequence');
const isSequence = value =>
value && typeof value[sequenceSymbol] === 'function';
export default class Factory {
static factoryMap = new Map();
... | [Directory structure > Addendum: Code summary]
```
```js title="src/core/factory.js"
import Model from '#src/core/model.js';
const sequenceSymbol = Symbol('sequence');
const isSequence = value =>
value && typeof value[sequenceSymbol] === 'function';
export default class Factory {
static factoryMap = new Map();
... | code_snippets | ||
a02a62fc-86c2-4904-99aa-b4583a56efb3 | 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 | 23 | SemanticChunker@1.0.0 | ae56b3488f1c6854015addacb4df5fea7240026a07fc6ca68d1e801724a90181 | [Directory structure > Addendum: Code summary]
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 | [Directory structure > Addendum: Code summary]
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',
... | [Directory structure > Addendum: Code summary]
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 | ||
aa7d01fd-7d98-45e3-a6fe-7d2737cc70c9 | 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 | 24 | SemanticChunker@1.0.0 | 7e8470dcfb611b3e29a41b7c3117929e982db7a5a7c25d6d29ff254a36800922 | [Directory structure > Addendum: Code summary]
```
```js title="spec/factories/postFactory.js"
import Factory from '#src/core/factory.js';
import Post from '#src/models/post.js';
const idSequence = Factory.sequence();
const titleSequence = Factory.sequence(n => `Post #${n}`);
const base = {
id: idSequence,
title:... | unknown | unknown | [Directory structure > Addendum: Code summary]
```
```js title="spec/factories/postFactory.js"
import Factory from '#src/core/factory.js';
import Post from '#src/models/post.js';
const idSequence = Factory.sequence();
const titleSequence = Factory.sequence(n => `Post #${n}`);
const base = {
id: idSequence,
title:... | [Directory structure > Addendum: Code summary]
```
```js title="spec/factories/postFactory.js"
import Factory from '#src/core/factory.js';
import Post from '#src/models/post.js';
const idSequence = Factory.sequence();
const titleSequence = Factory.sequence(n => `Post #${n}`);
const base = {
id: idSequence,
title:... | code_snippets | ||
aa7e41f5-5dc4-4656-9c97-c9520dd9040f | 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 | 18 | SemanticChunker@1.0.0 | a8be5a356d865031c02142e848e97be7a0518000c09e25420f13804d4439084a | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
Last but not least, here's a summary of the complete implementation. This includes all new classes, as well as previous one, so you can pick up where you left off next time.
You can also [browse through the Code Reference on GitHub](https://git... | unknown | unknown | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
Last but not least, here's a summary of the complete implementation. This includes all new classes, as well as previous one, so you can pick up where you left off next time.
You can also [browse through the Code Reference on GitHub](https://git... | [Directory structure > Addendum: Code summary]
## Addendum: Code summary
Last but not least, here's a summary of the complete implementation. This includes all new classes, as well as previous one, so you can pick up where you left off next time.
You can also [browse through the Code Reference on GitHub](https://git... | code_snippets | ||
dbe5d5f4-075b-4150-a9d5-a566c5f7c813 | 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 | 12 | SemanticChunker@1.0.0 | 07d9a2a839eb39222243e9ce3a8ce10f890d4f6d4e602b4eb68265dd709343b0 | [Directory structure > Sequences]
## Sequences
As you may have noticed in the previous example, we're always creating objects with the same `id`. This is fine for most cases, but it can become a problem when we need to test objects with unique identifiers. This is where **sequences** come in. Sequences are a way to g... | unknown | unknown | [Directory structure > Sequences]
## Sequences
As you may have noticed in the previous example, we're always creating objects with the same `id`. This is fine for most cases, but it can become a problem when we need to test objects with unique identifiers. This is where **sequences** come in. Sequences are a way to g... | [Directory structure > Sequences]
## Sequences
As you may have noticed in the previous example, we're always creating objects with the same `id`. This is fine for most cases, but it can become a problem when we need to test objects with unique identifiers. This is where **sequences** come in. Sequences are a way to g... | code_snippets | ||
e0f270fb-2f0d-4ec5-96e2-9b53da8f806b | 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 | 8 | SemanticChunker@1.0.0 | 81b01c2c3ff1793ad3e0b2c348f704d38dd250bc98101ba2aa5c729bdda1be84 | [The Factory class > Customizing objects]
> [!NOTE]
>
> Some of you might be wondering why I didn't choose to make the customized object contain functions, so that `email` can be specified as a function, instead of passing two parameters. This is a **design choice** I stand by, as the cost of calling a function for ea... | unknown | unknown | [The Factory class > Customizing objects]
> [!NOTE]
>
> Some of you might be wondering why I didn't choose to make the customized object contain functions, so that `email` can be specified as a function, instead of passing two parameters. This is a **design choice** I stand by, as the cost of calling a function for ea... | [The Factory class > Customizing objects]
> [!NOTE]
>
> Some of you might be wondering why I didn't choose to make the customized object contain functions, so that `email` can be specified as a function, instead of passing two parameters. This is a **design choice** I stand by, as the cost of calling a function for ea... | code_snippets |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.