Style Guide
The style guide is mostly based on author experience in using Marble.js on large production-ready projects following microservice/event-driven architecture style.

Project organization

Marble.js framework doesn't define any strict file structures and conventions from the organization-level perspective that each developer should enforce. Below you can find some useful hints that you can follow when organizing your Marble.js app.

Keep server and connected listeners in separate files

From the framework perspective, listeners and servers are separate layers that are responsible for different things. #createServer and similar factory functions are responsible for handling transport-layer-related processes, like: bootstrapping server and bounded context, listening for incoming messages or reacting for transport-layer events, where for the contrast, listeners are responsible for processing I/O messages that go through underlying transport layer in order to fulfill business needs. Basically, it is just about the single responsibility principle.
By convention Marble.js follows suffixed file naming which results in:
Server
Listener
http.server.ts
http.listener.ts
microservice.server.ts
microservice.listener.ts
websocket.server.ts
websocket.listener.ts
NONE
eventbus.listener.ts

Keep HTTP route with its corresponding HttpEffect

In Marble.js HTTP effects are tightly connected to the route on which they operate. Having them in a separation makes the code less readable and less understandable. Always try to keep them as a one unit. Every HttpEffect, that comes through r.pipe route builder, is accessible via .effect property of the returned RouteEffect object. It if you want to unit test only the effect function, that's the way of accessing it.
❌ Bad
getFoo.route.ts
getFoo.effect.ts
1
import { r } from '@marblejs/http';
2
import { getFooEffect } from './getFoo.effect';
3
4
const getFoo = r.pipe(
5
r.matchPath('/foo'),
6
r.matchType('GET'),
7
r.useEffect(getFooEffect));
Copied!
1
import { HttpEffect } from '@marblejs/http';
2
3
export const getFooEffect: HttpEffect = (req$, ctx) => req$.pipe(
4
...
5
);
Copied!
Good
getFoo.effect.ts
1
import { r } from '@marblejs/http';
2
3
const getFoo$ = r.pipe(
4
r.matchPath('/foo'),
5
r.matchType('GET'),
6
r.useEffect((req$, ctx) => req$.pipe(
7
...
8
)));
Copied!
Index files are good for combining and re-exporting related files as a one module.
1
/user
2
+ ── /getUserList
3
│ + ── getUserList.effect.spec.ts
4
│ └─── getUserList.effect.ts
5
6
+ ── /getUser
7
│ + ── getUser.effect.spec.ts
8
│ └─── getUser.effect.ts
9
10
+ ── /postUser
11
│ + ── getUser.effect.spec.ts
12
│ └─── getUser.effect.ts
13
14
└─── index.ts
15
Copied!
index.ts
http.listener.ts
1
import { combineRoutes } from '@marblejs/http';
2
3
export const user$ = combineRoutes('/user', {
4
middlewares: [
5
authorize$,
6
],
7
effects: [
8
getUserList$,
9
getUser$,
10
postUser$,
11
],
12
});
Copied!
1
import { httpListener } from '@marblejs/http';
2
import { user$ } from './user';
3
4
export const listener = httpListener({
5
effects: [
6
user$,
7
],
8
});
Copied!
Or in case of messaging/websockets effects:
index.ts
eventBus.listener.ts
1
import { combineEffects } from '@marblejs/core';
2
3
export const user$ = combineEffects(
4
userCreated$,
5
userRemoved$,
6
...
7
);
Copied!
1
import { messagingListener } from '@marblejs/messaging';
2
import { user$ } from './user';
3
4
export const listener = messagingListener({
5
effects: [
6
user$,
7
],
8
});
Copied!

Context

Token naming and creation

  • Use PascalCase naming convention with Token suffix for token definitions.
  • Always remember to define a context token name identifier. It will help you quickly recognize what dependency is missing when asking for it via useContext hook function.
  • Place token next to reader definition. It is easier to navigate to reader implementation via popular "Go to Implementation" mechanism.
Bad
tokens.ts
user.repository.ts
1
import { createContextToken } from '@marblejs/core';
2
3
export const userRepository = createContextToken<UserRepository>();
Copied!
1
import { createReader } from '@marblejs/core';
2
3
export const userRepository = createReader(() => ...);
Copied!
Good
user.repository
1
import { createContextToken, createReader } from '@marblejs/core';
2
3
export type UserRepository = ReturnType<typeof UserRepository>;
4
5
export const UserRepository = createReader(() => ...);
6
7
export const UserRepositoryToken = createContextToken<UserRepository>('UserRepository');
Copied!

Eager vs Lazy binding

Identify which dependencies should be bound to the app context eagerly (before app startup) and which lazily.
Given:
1
import { createContextToken, createReader } from '@marblejs/core';
2
3
export type DatabaseConnection = Connection;
4
5
export const DatabaseConnection = createReader(async _ => ...);
6
7
export const DatabaseConnectionToken = createContextToken<DatabaseConnection>('DatabaseConnection');
Copied!
Note that in case of async readers the type of created reader will be: Reader<Context, Promise<Connection>>
Bad
1
import { bindTo, bindLazilyTo, useContext } from '@marblejs/core';
2
3
const dependencies = [
4
bindTo(DatabaseConnectionToken)(DatabaseConnection),
5
// or
6
bindLazilyTo(DatabaseConnectionToken)(DatabaseConnection),
7
];
8
9
...
10
11
const connection = useContext(DatabaseConnectionToken)(ask);
12
13
// typeof connection === Promise<Connection>;
Copied!
Good
1
import { bindEagerlyTo, useContext } from '@marblejs/core';
2
3
const dependencies = [
4
bindEagerlyTo(DatabaseConnectionToken)(DatabaseConnection),
5
];
6
7
...
8
9
const connection = useContext(DatabaseConnectionToken)(ask);
10
11
// typeof connection === Connection;
Copied!

Injection

Always try to inject bound dependencies at the top level of your effects (before returned Observable stream). All effects are evaluated eagerly, so in case of missing context dependency the framework will be able to spot issues during initial bootstrap.
Bad
1
const postUser$ = r.pipe(
2
r.matchPath('/'),
3
r.matchType('POST'),
4
r.useEffect((req$, ask) => req$.pipe(
5
validateRequest,
6
mergeMap(req => {
7
const userRepository = useContext(UserRepositoryToken)(ask);
8
const { body } = req;
9
10
return userRepository
11
.persist(body)
12
.pipe(
13
mergeMap(userRepository.getById),
14
map(user => ({ body: user })),
15
);
16
}),
17
));
Copied!
Good
1
const postUser$ = r.pipe(
2
r.matchPath('/'),
3
r.matchType('POST'),
4
r.useEffect((req$, ask) => {
5
const userRepository = useContext(UserRepositoryToken)(ask);
6
7
return req$.pipe(
8
validateRequest,
9
map(req => req.body),
10
mergeMap(userRepository.persist),
11
mergeMap(userRepository.getById),
12
map(user => ({ body: user })),
13
);
14
}));
Copied!

Messaging

Event encoding/decoding

  • Use UPPER_SNAKE_CASE event type naming
  • Use enumerable string literal type or plain const record for gathering a map of all possible event types for given context
  • Use event builder for I/O encoding/decoding
  • Group your messages into Events, Commands and Queries (see: CQRS chapter)
Bad
user.event.ts
1
import { Event } from '@marblejs/core';
2
import * as t from 'io-ts';
3
4
export const UserCreated = (id: string): Event => ({
5
type: 'UserCreated',
6
payload: { id },
7
});
8
9
export const UserUpdated = (id: string): Event => ({
10
type: 'UserUpdated',
11
payload: { id },
12
});
13
14
export const UserCreatedCodec = t.type({
15
type: t.literal('UserCreated'),
16
payload: t.type({ id: t.string }),
17
});
18
19
export const UserUpdatedCodec = t.type({
20
type: t.literal('UserUpdated'),
21
payload: t.type({ id: t.string }),
22
});
Copied!
✅ Good
1
import { event } from '@marblejs/core';
2
import * as t from 'io-ts';
3
4
export enum UserEventType {
5
USER_CREATED = 'USER_CREATED',
6
USER_UPDATED = 'USER_UPDATED',
7
}
8
9
export const UserCreatedEvent =
10
event(UserEventType.USER_CREATED)(t.type({
11
id: t.string,
12
}));
13
14
export const UserUpdatedEvent =
15
event(UserEventType.USER_UPDATED)(t.type({
16
id: t.string,
17
}));
Copied!

Event matching and validation

  • Always try match events by event I/O codec - avoid raw literals since they don't carry the actual event payload type
  • Event-based communication follows the same laws as request-based communication - each incoming event should be validated before usage (eg. using previously mentioned event codec).
Bad
userCreated.effect.ts
1
import { act, matchEvent } from '@marblejs/core';
2
import { MsgEffect } from '@marblejs/messaging';
3
4
export const userCreated$: MsgEffect = event$ =>
5
event$.pipe(
6
// event payload is unknown, no type is inferred...
7
matchEvent('USER_CREATED'),
8
act(event => ...),
9
);
Copied!
❌ / ✅ Better
userCreated.effect.ts
1
import { act, matchEvent } from '@marblejs/core';
2
import { MsgEffect } from '@marblejs/messaging';
3
import { UserCreatedEvent } from './user.event.ts';
4
5
export const userCreated$: MsgEffect = event$ =>
6
event$.pipe(
7
// type is inferred but event still requires validation...
8
matchEvent(UserCreatedEvent),
9
act(event => ...),
10
);
Copied!
✅ Good
userCreated.effect.ts
1
import { act, matchEvent } from '@marblejs/core';
2
import { MsgEffect } from '@marblejs/messaging';
3
import { UserCreatedEvent } from './user.event.ts';
4
5
export const userCreated$: MsgEffect = event$ =>
6
event$.pipe(
7
matchEvent(UserCreatedEvent),
8
act(eventValidator$(UserCreatedEvent)),
9
act(event => ...),
10
);
Copied!

Effect output

  • Each processed event should be mapped to a different event type to avoid infinite-loops.
  • In case you don't want to emit anything in the effect stream you can skip emitted values, eg. by ignoreElements operator.
Bad
1
import { matchEvent } from '@marblejs/core';
2
import { MsgEffect } from '@marblejs/messaging';
3
4
const foo$: MsgEffect = event$ =>
5
event$.pipe(
6
matchEvent('FOO'),
7
tap(doSomeWork),
8
);
Copied!
✅ Good
1
import { act, matchEvent } from '@marblejs/core';
2
import { MsgEffect } from '@marblejs/messaging';
3
import { pipe } from 'fp-ts/lib/function';
4
5
const foo$: MsgEffect = event$ =>
6
event$.pipe(
7
matchEvent('FOO'),
8
act(event => pipe(
9
doSomeWork(event),
10
map(payload => ({ type: 'FOO_RESULT', payload })),
11
)),
12
);
Copied!

Error handling

  • Each messaging effect should handle errors in a disposable streams either via mergeMap/switchMap/... operators with combination of catchError or viaact operator.
Bad
1
import { matchEvent } from '@marblejs/core';
2
import { MsgEffect } from '@marblejs/messaging';
3
4
const foo$: MsgEffect = event$ =>
5
event$.pipe(
6
matchEvent('FOO'),
7
mergeMap(doSomeWork),
8
map(payload => ({ type: 'FOO_RESULT', payload }),
9
);
Copied!
Good
1
import { act, matchEvent } from '@marblejs/core';
2
import { MsgEffect } from '@marblejs/messaging';
3
import { pipe } from 'fp-ts/lib/function';
4
import { catchError } from 'rxjs/operators';
5
6
const foo$: MsgEffect = event$ =>
7
event$.pipe(
8
matchEvent('FOO'),
9
mergeMap(event => pipe(
10
doSomeWork(event),
11
map(payload => ({ type: 'FOO_RESULT', payload })),
12
catchError(error => ({ type: 'FOO_ERROR', error })),
13
)),
14
);
Copied!
✅ Even better
1
import { act, matchEvent } from '@marblejs/core';
2
import { MsgEffect } from '@marblejs/messaging';
3
import { pipe } from 'fp-ts/lib/function';
4
5
const foo$: MsgEffect = event$ =>
6
event$.pipe(
7
matchEvent('FOO'),
8
act(event => pipe(
9
doSomeWork(event),
10
map(payload => ({ type: 'FOO_RESULT', payload })),
11
)),
12
);
Copied!
Last modified 2mo ago