Skip to content

Commit

Permalink
fix: redis and core async (#155)
Browse files Browse the repository at this point in the history
fix: test
  • Loading branch information
AndrewHanasiro authored Oct 13, 2024
1 parent 27340f6 commit 029b32c
Show file tree
Hide file tree
Showing 20 changed files with 62 additions and 45 deletions.
6 changes: 3 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
FROM node:20.12.0-alpine3.18 AS dependency
FROM node:20.14.0-slim AS dependency
WORKDIR /app
COPY . .
RUN npm ci

FROM node:20.12.0-alpine3.18 AS builder
FROM node:20.14.0-slim AS builder
WORKDIR /app
COPY . .
COPY --from=dependency /app/node_modules ./node_modules
RUN npm run build

FROM node:20.12.0-alpine3.18 AS deploy
FROM node:20.14.0-slim AS deploy
WORKDIR /app
COPY --from=dependency /app/node_modules ./node_modules
COPY --from=builder /app/build ./build
Expand Down
13 changes: 6 additions & 7 deletions src/core/config/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,18 @@ import { getEnv } from '../../config/enviroment_config'
import logger from '../../config/logger'

let client: RedisClient
export function getRedis(url: string): RedisClient {
export async function getRedis(url: string): Promise<RedisClient> {
if (client != undefined) {
return client
} else {
client = createClient({
url: url ?? `redis://${getEnv().cache.url}`,
client = await createClient({
url: `redis://${url ?? getEnv().cache.url}`,
})
client.on('error', (error: Error) => {
logger.error('error on connecting:', error)
client.quit().finally(() => {
.on('error', (error: Error) => {
logger.error('error on connecting:', error)
throw error
})
})
.connect()
return client
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ import ResetPasswordUseCase from './usecases/reset_password.usecase'
import TokenUsecase from './usecases/token.usecase'
import UserUsecase from './usecases/user.usecase'

export function getCore() {
export async function getCore() {
const env = getEnv()
const database = getPostgres(env)
const cache = getRedis(env.cache.url)
const cache = await getRedis(env.cache.url)
const kafka = getKafka(env)
// SERVICES
const passwordService = new PasswordService()
Expand Down
3 changes: 3 additions & 0 deletions src/core/providers/token.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ export class TokenRepository
constructor(private cache: RedisClient) {}

async invalidate(token: string): Promise<void> {
if (!this.cache.isReady) {
await this.cache.connect()
}
await this.cache.set(token, token)
await this.cache.expire(token, this.TTL)
}
Expand Down
4 changes: 2 additions & 2 deletions src/core/services/password.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { genSaltSync, hash as hashFunc, compare } from 'bcrypt'
import { genSaltSync, hash as hashFunc, compareSync } from 'bcrypt'
import zxcvbn from 'zxcvbn'

export class PasswordService {
Expand All @@ -9,7 +9,7 @@ export class PasswordService {
}

async compare(password: string, hash: string): Promise<boolean> {
return compare(password, hash)
return compareSync(password, hash)
}

checkEntropy(password: string, dictionary: string[]): boolean {
Expand Down
6 changes: 4 additions & 2 deletions src/presentation/http/routes/login.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ loginRoute.post('/', (async (
) => {
try {
const { email, password }: LoginInput = await schema.validateAsync(req.body)
const resp = await getCore().login.login(email, password)
const core = await getCore()
const resp = await core.login.login(email, password)
res.status(200).send(resp)
} catch (error) {
next(error)
Expand All @@ -46,7 +47,8 @@ loginRoute.get('/refresh/:token', jwtMiddleware, (async (
) => {
try {
const token = req.params.token
const resp = await getCore().token.refresh(token)
const core = await getCore()
const resp = await core.token.refresh(token)
res.status(200).send(resp)
} catch (error) {
next(error)
Expand Down
3 changes: 2 additions & 1 deletion src/presentation/http/routes/logout.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ logoutRoute.post('/', (async (
) => {
try {
const token = retriveToken(req)
await getCore().logout.logout(token)
const core = await getCore()
await core.logout.logout(token)
res.status(200).send('Ok')
} catch (error) {
next(error)
Expand Down
15 changes: 10 additions & 5 deletions src/presentation/http/routes/mfa.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ mfaRoute.get('/:id', (async (
) => {
try {
const userId: string = req.params.id
const resp = await getCore().mfa.list(userId)
const core = await getCore()
const resp = await core.mfa.list(userId)
res.status(200).send({ resp })
} catch (error) {
next(error)
Expand All @@ -36,7 +37,8 @@ mfaRoute.post('/validate', (async (
) => {
try {
const mfaId: string = req.body.id
const resp = await getCore().mfa.validate(mfaId)
const core = await getCore()
const resp = await core.mfa.validate(mfaId)
res.status(200).send({ resp })
} catch (error) {
next(error)
Expand All @@ -63,7 +65,8 @@ mfaRoute.post('/choose', (async (
const { hash, strategy }: LoginMFAChooseInput = await schema.validateAsync(
req.body
)
const resp = await getCore().mfaChoose.choose(hash, strategy)
const core = await getCore()
const resp = await core.mfaChoose.choose(hash, strategy)
res.status(200).send({ hash: resp })
} catch (error) {
next(error)
Expand All @@ -88,7 +91,8 @@ mfaRoute.post('/code', (async (
const { hash, code }: LoginMFACodeInput = await schema2.validateAsync(
req.body
)
const credential = await getCore().mFACode.find(hash, code)
const core = await getCore()
const credential = await core.mFACode.find(hash, code)
res.status(200).send(credential)
} catch (error) {
next(error)
Expand All @@ -111,7 +115,8 @@ mfaRoute.post('/', (async (req: Request, res: Response, next: NextFunction) => {
const { userId, strategy }: MFACreateInput = await schema3.validateAsync(
req.body
)
const mfaId = await getCore().mfa.create(userId, strategy)
const core = await getCore()
const mfaId = await core.mfa.create(userId, strategy)
res.status(200).send({ mfaId })
} catch (error) {
next(error)
Expand Down
13 changes: 6 additions & 7 deletions src/presentation/http/routes/organization.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ organizationRoute.post('/', (async (
const { name, parentId }: OrganizationInput = await schema.validateAsync(
req.body
)
const id = await getCore().organization.create(name, parentId)
const core = await getCore()
const id = await core.organization.create(name, parentId)
res.status(200).send({ id })
} catch (error) {
next(error)
Expand All @@ -56,7 +57,8 @@ organizationRoute.post('/add', (async (
try {
const { organizationId, userId }: OrganizationAddUserInput =
await schema2.validateAsync(req.body)
const resp = await getCore().organization.addUser(organizationId, userId)
const core = await getCore()
const resp = await core.organization.addUser(organizationId, userId)
res.status(200).send({ result: resp })
} catch (error) {
next(error)
Expand All @@ -82,11 +84,8 @@ organizationRoute.patch('/', (async (
try {
const { organizationId, name, parentId }: OrganizationUpdateUserInput =
await schema3.validateAsync(req.body)
const resp = await getCore().organization.update(
organizationId,
name,
parentId
)
const core = await getCore()
const resp = await core.organization.update(organizationId, name, parentId)
res.status(200).send({ result: resp })
} catch (error) {
next(error)
Expand Down
6 changes: 4 additions & 2 deletions src/presentation/http/routes/reset_password.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ resetPasswordRoute.post('/forget', (async (
) => {
try {
const { email }: ForgetPasswordInput = await schema.validateAsync(req.body)
const resp = await getCore().reset.forget(email)
const core = await getCore()
const resp = await core.reset.forget(email)
res.status(200).send(resp)
} catch (error) {
next(error)
Expand All @@ -54,7 +55,8 @@ resetPasswordRoute.post('/recover', (async (
try {
const { password, hash }: RecoverPasswordInput =
await schema2.validateAsync(req.body)
const resp = await getCore().reset.recover(password, hash)
const core = await getCore()
const resp = await core.reset.recover(password, hash)
res.status(200).send(resp)
} catch (error) {
next(error)
Expand Down
9 changes: 6 additions & 3 deletions src/presentation/http/routes/user.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ userRoute.post('/', (async (
const { name, email, password }: UserInput = await schema.validateAsync(
req.body
)
const id = await getCore().user.create(name, email, password)
const core = await getCore()
const id = await core.user.create(name, email, password)
res.status(201).send({ id })
} catch (error) {
next(error)
Expand Down Expand Up @@ -66,7 +67,8 @@ userRoute.patch('/', (async (
try {
const { userId, name, email, phone, deviceId, gaToken }: UserInfoInput =
await schema2.validateAsync(req.body)
const resp = await getCore().user.update({
const core = await getCore()
const resp = await core.user.update({
userId,
name,
email,
Expand All @@ -82,7 +84,8 @@ userRoute.patch('/', (async (

userRoute.get('/', (async (req: Request, res: Response, next: NextFunction) => {
try {
const resp = await getCore().user.list()
const core = await getCore()
const resp = await core.user.list()
res.status(200).send({ list: resp })
} catch (error) {
next(error)
Expand Down
9 changes: 6 additions & 3 deletions src/presentation/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import { registerInstrumentations } from '@opentelemetry/instrumentation'
import { Resource } from '@opentelemetry/resources'
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base'
import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'
import {
ATTR_SERVICE_NAME,
ATTR_SERVICE_VERSION,
} from '@opentelemetry/semantic-conventions'

import { getEnv } from '../config/enviroment_config'

Expand All @@ -18,8 +21,8 @@ registerInstrumentations({

const resource = Resource.default().merge(
new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: getEnv().app.name,
[SemanticResourceAttributes.SERVICE_VERSION]: '0.1.0',
[ATTR_SERVICE_NAME]: getEnv().app.name,
[ATTR_SERVICE_VERSION]: '0.1.0',
})
)

Expand Down
2 changes: 1 addition & 1 deletion test/integration/http/login.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ describe('Login Route', () => {
redisContainer = await new RedisContainer().start()
database = await setupDB(pgSqlContainer)
userFixture = await insertUserIntoDatabase(database)
redis = getRedis(redisContainer.getConnectionUrl())
redis = await getRedis(redisContainer.getConnectionUrl())
if (!redis.isReady) {
await redis.connect()
}
Expand Down
2 changes: 1 addition & 1 deletion test/integration/http/logout.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ describe('Logout Route', () => {

beforeAll(async () => {
redisContainer = await new RedisContainer().start()
redis = getRedis(redisContainer.getConnectionUrl())
redis = await getRedis(redisContainer.getConnectionUrl())
if (!redis.isReady) {
await redis.connect()
}
Expand Down
2 changes: 1 addition & 1 deletion test/integration/http/mfa.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('MFA Route', () => {
redisContainer = await new RedisContainer().start()
database = await setupDB(pgSqlContainer)
const userFixture = await insertUserIntoDatabase(database)
redis = getRedis(redisContainer.getConnectionUrl())
redis = await getRedis(redisContainer.getConnectionUrl())
if (!redis.isReady) {
await redis.connect()
}
Expand Down
2 changes: 1 addition & 1 deletion test/integration/http/organization.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('Organization Route', () => {
redisContainer = await new RedisContainer().start()
database = await setupDB(pgSqlContainer)
managerFixture = await insertUserIntoDatabase(database)
redis = getRedis(redisContainer.getConnectionUrl())
redis = await getRedis(redisContainer.getConnectionUrl())
if (!redis.isReady) {
await redis.connect()
}
Expand Down
2 changes: 1 addition & 1 deletion test/integration/http/reset_password.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ describe('Reset Password Route', () => {
redisContainer = await new RedisContainer().start()
database = await setupDB(pgSqlContainer)
managerFixture = await insertUserIntoDatabase(database)
redis = getRedis(redisContainer.getConnectionUrl())
redis = await getRedis(redisContainer.getConnectionUrl())
if (!redis.isReady) {
await redis.connect()
}
Expand Down
2 changes: 1 addition & 1 deletion test/integration/http/user.route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('User Route', () => {
redisContainer = await new RedisContainer().start()
database = await setupDB(pgSqlContainer)
managerFixture = await insertUserIntoDatabase(database)
redis = getRedis(redisContainer.getConnectionUrl())
redis = await getRedis(redisContainer.getConnectionUrl())
if (!redis.isReady) {
await redis.connect()
}
Expand Down
2 changes: 1 addition & 1 deletion test/unit/providers/mfa_choose.repository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe('mfa_choose repository', () => {

beforeAll(async () => {
redisContainer = await new RedisContainer().start()
redis = getRedis(redisContainer.getConnectionUrl())
redis = await getRedis(redisContainer.getConnectionUrl())
if (!redis.isReady) {
await redis.connect()
}
Expand Down
2 changes: 1 addition & 1 deletion test/unit/providers/mfa_code.repository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('mfa_code repository', () => {

beforeAll(async () => {
redisContainer = await new RedisContainer().start()
redis = getRedis(redisContainer.getConnectionUrl())
redis = await getRedis(redisContainer.getConnectionUrl())
if (!redis.isReady) {
await redis.connect()
}
Expand Down

0 comments on commit 029b32c

Please sign in to comment.