1.3.3 • Published 3 years ago

@bloc-arch/core v1.3.3

Weekly downloads
54
License
MIT
Repository
github
Last release
3 years ago

@bloc-arch/core

https://travis-ci.com/kasperski95/bloc-arch--core.svg?branch=master Coverage Status

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

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 {}
1.3.3

3 years ago

1.3.2

3 years ago

1.3.1

3 years ago

1.3.0

3 years ago

1.2.1

3 years ago

1.2.0

3 years ago

1.1.0

3 years ago

1.0.0

3 years ago