@bloc-arch/core
v1.3.3
Published
State management module for JS and TS.
Downloads
19
Maintainers
Readme
@bloc-arch/core
BLoC (Business Logic Component) is the most popular architecture (pattern) for Flutter development introduced at Google I/O in 2019.
This package provides essential logic to recreate this pattern in JavaScript (and TypeScript).
Table of Contents
Related packages
Diagram
Usage Example
// UserBloc.ts:
import { Bloc } from '@bloc-arch/core'
import * as UserEvents from './UserEvent'
import * as UserStates from './UserState'
export class UserBloc extends Bloc<UserEvents.UserEvent, UserStates.UserState> {
public jwt: string | undefined
constructor(
private authRepository: AuthRepository,
private userRepository: UserRepository
) {
super(new UserStates.Authenticating())
}
async *mapEventToState(event: UserEvents.UserEvent) {
if (event instanceof UserEvents.Authenticate) {
yield new UserStates.Authenticating()
this.jwt = await this.authRepository.authenticate(
event.login,
event.password
)
if (!this.jwt) {
yield new UserStates.Anonymous()
} else {
const user = await this.userRepository.me(this.jwt)
if (user.role === 'admin') {
yield new UserStates.Administrator(user.username)
} else {
yield new UserStates.Authenticated(user.username)
}
}
} else if (event instanceof UserEvents.LogOut) {
this.jwt = undefined
yield new UserStates.Anonymous()
}
}
}
// UserState.ts:
import { BlocState } from '@bloc-arch/core'
export abstract class UserState extends BlocState {}
export class Authenticating extends UserState {}
export class Anonymous extends UserState {}
export class Authenticated extends UserState {
constructor(public username: string) {
super()
}
}
export class Administrator extends Authenticated {}
// UserEvent.ts:
import { BlocEvent } from '@bloc-arch/core'
export abstract class UserEvent extends BlocEvent {}
export class Authenticate extends UserEvent {
constructor(public login: string, public password: string) {
super()
}
}
export class LogOut extends UserEvent {}