3.0.8 • Published 1 day ago

@beecode/msh-node-session v3.0.8

Weekly downloads
80
License
mit
Repository
github
Last release
1 day ago

Build Status codecov GitHub license
NPM

msh-node-session

Micro-service helper: node error

This project is intended to be used in typescript project.

Install

npm i @beecode/msh-node-session

Diagram

vision-diagram

Usage

Util implementation example

Class extension

// src/util/session-util.ts

import { NodeSessionUtil } from '@beecode/msh-node-session/dist/node-session-util'
import { FastAlsStrategy } from '@beecode/msh-node-session/dist/session-strategy/fast-als-strategy'
// import { ClsHookedStrategy } from '@beecode/msh-node-session/dist/session-strategy/cls-hooked-strategy'
import { SessionStrategy } from '@beecode/msh-node-session/dist/session-strategy/session-strategy'
import { cacheUtil } from '@beecode/msh-node-util/lib/cache-util.js'

export enum SessionData {
  TYPEORM_ENTITY_MANAGER = 'typeorm-entity-manager',
  AUTH_USER = 'auth-user',
}

export class SessionUtil extends NodeSessionUtil {

  public constructor(params?: { sessionStrategy?: SessionStrategy }) {
    const { sessionStrategy } = params ?? {}
    super({ sessionStrategy })
  }

  public getTransactionManager(): EntityManager | undefined {
    try {
      return this._strategy.get<EntityManager>(SessionData.TYPEORM_ENTITY_MANAGER)
    } catch (_err) {
      return undefined
    }
  }

  protected _setTransactionManager(entityManager: EntityManager): void {
    return this._strategy.set<EntityManager>(SessionData.TYPEORM_ENTITY_MANAGER, entityManager)
  }
  
  public async startTransaction<T>(callback: (transactionEntityManager: EntityManager) => Promise<T>): Promise<T> {
    return this.createAsyncSession(() => {
      const existingTransactionManager = this.getTransactionManager()
      if (existingTransactionManager) return callback(existingTransactionManager)
      return databaseService.getConnection().transaction<T>((newTransEntityManager: EntityManager) => {
        this._setTransactionManager(newTransEntityManager)
        return callback(newTransEntityManager)
      })
    })
  }

  public setAuthUser(authUser: JWTPayloadUser): void {
    this._strategy.set<JWTPayloadUser>(SessionData.AUTH_USER, authUser)
  }

  public getAuthUser(): JWTPayloadUser {
    const authUser = this._strategy.get<JWTPayloadUser>(SessionData.AUTH_USER)
    if (!authUser) throw error.server.internalServerError('Missing auth user from session')
    return authUser
  }

  /**
   * Connect to existing transaction, this is only used in migrations files
   * @param {EntityManager} entityManager
   * @param {() => Promise<T>} callback
   * @returns {Promise<T>}
   */
  public async entityManagerSideCall<T>(entityManager: EntityManager, callback: () => Promise<T>): Promise<T> {
    return this.createAsyncSession(async () => {
      this._setTransactionManager(entityManager)
      return callback()
    })
  }
}

export const sessionStrategy = new FastAlsStrategy()
// export const sessionStrategy = new ClsHookedStrategy()
export const sessionUtil = cacheUtil.singleton(() => new SessionUtil({ sessionStrategy }))

Fastify middleware example

import Fastify from 'fastify'
import { fastifyHelperFactory } from '@beecode/msh-node-session/dist/helpers/fastify-helper'
import { sessionStrategy } from 'src/util/session-util'


const fastify = Fastify()

const fastifyHelper = fastifyHelperFactory({sessionStrategy})

await fastify.register(fastifyHelper.beecodeSessionContextPluginFactory())

Express middleware example

FastAls

import express from 'express'
import { expressFastAlsHelperFactory } from '@beecode/msh-node-session/dist/helpers/express-fast-als-helper'
import { sessionStrategy } from 'src/util/session-util'

const expressApp = express()

const expressFastAlsHelper = expressFastAlsHelperFactory({fastAlsStrategy:sessionStrategy})
this._expressApp.use((req, res, next) => expressFastAlsHelper.expressMiddleware(req, res, next))
// other middlewares
// expressApp.use(... 

ClsHooked

import express from 'express'
import { expressClsHookedHelperFactory } from '@beecode/msh-node-session/dist/helpers/express-cls-hooked-helper'
import { sessionStrategy } from 'src/util/session-util'

const expressApp = express()

const expressClsHookedHelperHelper = expressClsHookedHelperFactory({fastAlsStrategy:sessionStrategy})
this._expressApp.use((req, res, next) => expressClsHookedHelperHelper.expressMiddleware(req, res, next))
this._expressApp.use((req, res, next) => expressClsHookedHelperHelper.expressMiddlewareBindEmitter(req, res, next))
// other middlewares
// expressApp.use(... 
3.0.8

1 day ago

3.0.7

5 days ago

3.0.6

6 days ago

3.0.5

9 days ago

3.0.4

24 days ago

3.0.3

30 days ago

3.0.2

30 days ago

3.0.1

1 month ago

3.0.0

1 month ago

2.2.6

12 months ago

2.2.5

1 year ago

2.2.4

2 years ago

2.2.3

2 years ago

2.2.1-alpha

2 years ago

2.2.2-alpha

2 years ago

2.2.0-alpha

2 years ago

2.1.0

2 years ago

2.0.0

2 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0-alpha

3 years ago