Node.js
CQRS
Learn the CQRS pattern.
What is CQRS?
CQRS (Command Query Responsibility Segregation) separates the write (command) and read (query) models. Commands change state, queries read state. The two models may live in separate databases or table sets.
A cqrsModel(cmd, query) function models this split: it returns {command: cmd, query: query}. Example: cqrsModel('CreateUser', 'GetUser') returns {command: 'CreateUser', query: 'GetUser'}. Splitting command and query lets the read side be optimized (a materialized view, for instance). Combined with event sourcing, commands produce events, and queries read from a view projected out of the events.
Command and query split
A command changes state: CreateUser, UpdateOrder. A query reads state: GetUser, ListOrders. CQRS manages these two sides with separate models so each can be optimized for its own needs.
Example: cqrsModel('CreateUser', 'GetUser') keeps the two fields apart. The write side may use normalized tables, the read side a materialized view. model.command marks the write task, model.query the read task. This split pays off when reads are far more frequent, such as social feeds. Combined with event sourcing, commands produce events, and queries read from a view projected from those events.
Exercise Write the CQRS model function
Write function cqrsModel(cmd, query). Return { command: cmd, query: query }. Define const model = cqrsModel('CreateUser', 'GetUser'). Print console.log(model.command) and console.log(model.query).
Show example solution
function cqrsModel(cmd, query) {
return { command: cmd, query: query };
}
const model = cqrsModel('CreateUser', 'GetUser');
console.log(model.command);
console.log(model.query);
Test yourself
-
Complete the object property
return { command: cmd, ____: query };
Show answer
return { command: cmd, query: query };
-
What does CQRS separate?
cqrsModel('CreateUser', 'GetUser')
- Yazma ve silme
- Database and table
- Sunucu ve istemci
- Komut ve sorgu
Show answer
Komut ve sorgu — CQRS separates the command (write) and query (read) models.
-
Match each piece to its role
- command
- Changes state
- query
- Reads state
- CreateUser
- A command
- GetUser
- A query
Next lesson: Summary - Distributed systems