thespringway
v1.0.4
Published
Package that add the @Service and @Repository in typescript like a Spring Framework
Maintainers
Readme
The Spring Way
This project is a lightweight annotation-based utility that brings Spring Boot-style notation to TypeScript. It is designed for developers coming from the Spring Boot ecosystem who want a smoother transition to TS while keeping a familiar architectural style.
Installation
npm install thespringwayUsage
This package provides two decorators, @Repository and @Service, which can be integrated as shown below (example only).
Setup
First you need to add the following configuration to your tsconfig.json file:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "ES2020",
}
}Services
In this case, simply adding the @Service() annotation is enough.
import { Service } from 'thespringway'
@Service()
export class LoginUseCase {
constructor(
private readonly repository: AuthRepository,
private readonly crypt: CryptRepository,
private readonly jwt: JwtRepository
) {}
async login(input: LoginInput): Promise<LoginOutput> {
const user = this.repository.getByEmail(input.email)
if (!user || !user.active || !user.password) throw new Error('User not found')
if (!(this.crypt.compare(input.passwowrd, user.password))) throw new Error('Password incorrect')
return {
token: this.jwt.sign(user),
session: user
}
}
}Repositories
Here we define two classes: one for the repository contract and another for its final implementation with the corresponding annotation.
import { Repository } from 'thespringway'
export abstract class AuthRepository {
abstract getByEmail(email: string): AuthStore | null
}
@Repository(AuthRepository)
export class LocalAuthRepository extends AuthRepository {
getByEmail(email: string): AuthStore | null{
if (email !== '[email protected]') return null
return {
id: 1,
name: 'admin',
email: '[email protected]',
password: '$2a$10$hXTzALcJ5a6tscposYW81OSMbXxrORVllKj4WGKpnazCbFWE3p.2W',
active: true
}
}
}Final Usage
To use the service/use case, call the resolve function included in the package. It resolves and injects the service dependencies automatically.
import { resolve } from 'thespringway'
const loginUseCase = resolve(LoginUseCase)
loginUseCase.login({ email: '[email protected]', password: 'password' })