CodeBlanks Logo Icon CodeBlanks

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.

Practice 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).

Starter code

index.js
// Write the cqrsModel function
// Return an object holding a command and a query
// Call with 'CreateUser' and 'GetUser', print both fields
// write here

Sample solution

index.js
function cqrsModel(cmd, query) {
  return { command: cmd, query: query };
}
const model = cqrsModel('CreateUser', 'GetUser');
console.log(model.command);
console.log(model.query);

Expected output

CreateUser
GetUser

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the object property

Question
return { command: cmd, ____: query };
Answer
return { command: cmd, query: query };

Explanation: The read side is named 'query'.

2 What does CQRS separate?

index.js
cqrsModel('CreateUser', 'GetUser')
  • Yazma ve silme
  • Database and table
  • Sunucu ve istemci
  • Komut ve sorgu Correct answer

Explanation: CQRS separates the command (write) and query (read) models.

3 Match each piece to its role

Term Meaning
command Changes state
query Reads state
CreateUser A command
GetUser A query

All lessons in Expert