Skip to content

Commit

Permalink
wip chapter 7
Browse files Browse the repository at this point in the history
  • Loading branch information
lmammino committed Dec 24, 2024
1 parent fb1cc74 commit e80828c
Show file tree
Hide file tree
Showing 26 changed files with 1,376 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# 07-revealing-constructor-immutable-buffer

This example demonstrate how to use the revealing constructor pattern to
implement an immutable buffer.

## Run

To run the example launch:

```bash
node index.js
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const MODIFIER_NAMES = ['swap', 'write', 'fill']

export class ImmutableBuffer {
constructor(size, executor) {
const buffer = Buffer.alloc(size)
const modifiers = {}
for (const prop in buffer) {
if (typeof buffer[prop] !== 'function') {
continue
}

if (MODIFIER_NAMES.some(m => prop.startsWith(m))) {
modifiers[prop] = buffer[prop].bind(buffer)
} else {
this[prop] = buffer[prop].bind(buffer)
}
}

executor(modifiers)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ImmutableBuffer } from './immutableBuffer.js'

const hello = 'Hello!'
const immutable = new ImmutableBuffer(hello.length, ({ write }) => {
write(hello)
})

console.log(String.fromCharCode(immutable.readInt8(0)))

// the following line will throw
// "TypeError: immutable.write is not a function"

// immutable.write('Hello?')
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "07-revealing-constructor-immutable-buffer",
"version": "1.0.0",
"description": "This example demonstrate how to use the revealing constructor pattern to implement an immutable buffer",
"type": "module",
"scripts": {},
"engines": {
"node": ">=22"
},
"engineStrict": true,
"keywords": [],
"author": "Luciano Mammino and Mario Casciaro",
"license": "MIT",
"dependencies": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
!/node_modules/
!/node_modules/*/node_modules
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# 08-singleton-false-uniqueness

This example demonstrate how under certain conditions, an instance exported by a
module stops to be a Singleton.

## Run

To run the example launch:

```bash
node index.js
```

NOTE: Don't run `npm install` or the since this sample is composed of some fake
dependencies which otherwise might be overwritten.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { getDbInstance as getDbFromA } from 'package-a'
import { getDbInstance as getDbFromB } from 'package-b'

const isSame = getDbFromA() === getDbFromB()
console.log(
`Is the db instance in package-a the same as package-b? ${isSame ? 'YES' : 'NO'}`
)

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "08-singleton-false-uniqueness",
"version": "1.0.0",
"description": "This example demonstrate how under certain conditions, an instance exported by a module stops to be a Singleton",
"type": "module",
"scripts": {},
"engines": {
"node": ">=22"
},
"engineStrict": true,
"keywords": [],
"author": "Luciano Mammino and Mario Casciaro",
"license": "MIT",
"dependencies": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
data.sqlite
20 changes: 20 additions & 0 deletions 07-creational-design-patterns/09-singleton-dependencies/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# 09-singleton-dependencies

This example shows how to wire dependencies using the singleton pattern

## Dependencies

Install all necessary dependencies with:

```shell script
npm install
```

## Run

To run the example:

```shell script
node import-posts.js
node index.js
```
28 changes: 28 additions & 0 deletions 07-creational-design-patterns/09-singleton-dependencies/blog.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { db } from './db.js'

export class Blog {
initialize() {
const initQuery = `CREATE TABLE IF NOT EXISTS posts (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);`

return db.run(initQuery)
}

createPost(id, title, content, createdAt) {
return db.run(
'INSERT INTO posts VALUES (?, ?, ?, ?)',
id,
title,
content,
createdAt
)
}

getAllPosts() {
return db.all('SELECT * FROM posts ORDER BY created_at DESC')
}
}
8 changes: 8 additions & 0 deletions 07-creational-design-patterns/09-singleton-dependencies/db.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { join } from 'node:path'
import { open } from 'sqlite'
import sqlite3 from 'sqlite3'

export const db = await open({
filename: join(import.meta.dirname, 'data.sqlite'),
driver: sqlite3.Database,
})
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Blog } from './blog.js'

const posts = [
{
id: 'my-first-post',
title: 'My first post',
content: 'Hello World!\nThis is my first post',
// biome-ignore lint/style/useNamingConvention: db mapping
created_at: new Date('2020-02-03'),
},
{
id: 'iterator-patterns',
title: 'Node.js iterator patterns',
content: "Let's talk about some iterator patterns in Node.js\n\n...",
// biome-ignore lint/style/useNamingConvention: db mapping
created_at: new Date('2020-02-06'),
},
{
id: 'dependency-injection',
title: 'Dependency injection in Node.js',
content:
'Today we will discuss about dependency injection in Node.js\n\n...',
// biome-ignore lint/style/useNamingConvention: db mapping
created_at: new Date('2020-02-29'),
},
// ...
]

const blog = new Blog()
await blog.initialize()

await Promise.all(
posts.map(post =>
blog.createPost(post.id, post.title, post.content, post.created_at)
)
)
console.log('All posts imported')
18 changes: 18 additions & 0 deletions 07-creational-design-patterns/09-singleton-dependencies/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Blog } from './blog.js'

const blog = new Blog()
await blog.initialize()
const posts = await blog.getAllPosts()
if (posts.length === 0) {
console.log(
'No post available. Run `node import-posts.js`' +
' to load some sample posts'
)
}

for (const post of posts) {
console.log(post.title)
console.log('-'.repeat(post.title.length))
console.log(`Published on ${new Date(post.created_at).toISOString()}`)
console.log(post.content)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "09-singleton-dependencies",
"version": "1.0.0",
"description": "This example shows how to wire dependencies using the singleton pattern",
"type": "module",
"scripts": {},
"engines": {
"node": ">=22"
},
"engineStrict": true,
"keywords": [],
"author": "Luciano Mammino and Mario Casciaro",
"license": "MIT",
"dependencies": {
"sqlite": "^5.1.1",
"sqlite3": "^5.1.7"
}
}
Loading

0 comments on commit e80828c

Please sign in to comment.