Skip to content

Commit

Permalink
update code
Browse files Browse the repository at this point in the history
  • Loading branch information
hudy9x committed Mar 14, 2024
1 parent 049f1ac commit 38dfb48
Show file tree
Hide file tree
Showing 13 changed files with 314 additions and 111 deletions.
10 changes: 10 additions & 0 deletions packages/be-gateway/src/events/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { connectSubClient } from '@shared/pubsub'
import { NotificationEvent } from './notification.event'
import { ReminderEvent } from './reminder.event'

export const CHANNEL_SCHEDULER_ACTION_NOTIFY = 'scheduler:action-notify'
export const CHANNEL_SCHEDULER_CREATE = 'scheduler:create'
export const CHANNEL_RUN_EVERY_MINUTE = 'fixed:run-every-minute'
export const EVENT = {
SCHEDULER_DELETE: 'scheduler:delete'
}
Expand All @@ -11,14 +13,22 @@ connectSubClient((err, redis) => {
if (err) {
return
}
// We must subscribe channels first
redis.subscribe(CHANNEL_SCHEDULER_ACTION_NOTIFY, (err, count) => {
console.log('subscribed', CHANNEL_SCHEDULER_ACTION_NOTIFY)
})

redis.subscribe(CHANNEL_RUN_EVERY_MINUTE)

// After that, we can listen messages from them
redis.on('message', async (channel: string, data: string) => {
if (channel === CHANNEL_SCHEDULER_ACTION_NOTIFY) {
const event = new NotificationEvent()
event.run(data)
}
if (channel === CHANNEL_RUN_EVERY_MINUTE) {
const reminder = new ReminderEvent()
reminder.run()
}
})
})
22 changes: 22 additions & 0 deletions packages/be-gateway/src/events/reminder.event.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { notifyToWebUsers } from '../lib/buzzer'
import { findCache, getJSONCache } from '../lib/redis'
import { extracDatetime, padZero } from '@shared/libs'
export class ReminderEvent {
async run() {
const { y, m, d, hour, min } = extracDatetime(new Date())

const key = [
`remind-${y}-${padZero(m)}-${padZero(d)}-${padZero(hour)}:${padZero(min)}`
]

const results = await findCache(key)

console.log('keys list', results)
if (!results.length) return

results.forEach(k => {
const res = getJSONCache([k])
console.log(res)
})
}
}
7 changes: 7 additions & 0 deletions packages/be-gateway/src/exceptions/InternalErrorException.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default class InternalErrorException extends Error {
status: number
constructor(message?: string) {
super(message || 'INTERNAL_SERVER_ERROR')
this.status = 500
}
}
16 changes: 12 additions & 4 deletions packages/be-gateway/src/lib/redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,20 +93,27 @@ export const genKeyFromSource = (source: { [key: string]: unknown }) => {

export const setJSONCache = (
key: CACHE_KEY,
value: RedisJSONValue | RedisJSONValue[]
value: RedisJSONValue | RedisJSONValue[],
expired?: number
) => {
if (!connected) {
return null
}
try {
const cacheKey = genKey(key)
console.log('cachekey', cacheKey, expired)
redis.set(cacheKey, JSON.stringify(value))
redis.expire(cacheKey, DAY)
redis.expire(cacheKey, expired || DAY)
} catch (error) {
console.log('set redis cache error')
}
}

export const setCacheExpire = (key: CACHE_KEY, expired: number) => {
const cacheKey = genKey(key)
redis.expire(cacheKey, expired)
}

export const getJSONCache = async (key: CACHE_KEY) => {
if (!connected) {
return null
Expand Down Expand Up @@ -147,10 +154,11 @@ export const delMultiCache = async (keys: CACHE_KEY[]) => {
await pipeline.exec()
}

export const findCache = async (key: CACHE_KEY) => {
export const findCache = async (key: CACHE_KEY, abs = false) => {
try {
const newKey = genKey(key)
const results = await redis.keys(newKey + '*')
const asterisk = abs ? '' : '*'
const results = await redis.keys(newKey + asterisk)
return results
} catch (error) {
console.log('find cache key error', error)
Expand Down
4 changes: 3 additions & 1 deletion packages/be-gateway/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import './events'
import Routes from './routes'
// import { Log } from './lib/log'

connectPubClient()
connectPubClient(err => {
console.log(err)
})
const app: Application = express()

app.get('/check-health', (req, res) => {
Expand Down
103 changes: 12 additions & 91 deletions packages/be-gateway/src/routes/task/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
} from '../../services/todo.counter'
import ActivityService from '../../services/activity.service'
import { createModuleLog } from '../../lib/log'
import TaskService from '../../services/task.service'

const logging = createModuleLog('ProjectTask')
// import { Log } from '../../lib/log'
Expand Down Expand Up @@ -258,100 +259,17 @@ router.post('/project/task/make-cover', async (req: AuthRequest, res) => {

// It means POST:/api/example
router.post('/project/task', async (req: AuthRequest, res) => {
const body = req.body as Task
const activityService = new ActivityService()
const {
desc,
visionId,
assigneeIds,
title,
dueDate,
projectId,
priority,
progress
} = req.body as Task
let taskStatusId = body.taskStatusId
const { id } = req.authen

const key = [CKEY.TASK_QUERY, projectId]
const counterKey = [CKEY.PROJECT_TASK_COUNTER, projectId]

try {
const doneStatus = await mdTaskStatusWithDoneType(projectId)

const done = doneStatus && doneStatus.id === taskStatusId ? true : false

if (!taskStatusId) {
const todoStatus = await mdTaskStatusWithTodoType(projectId)
taskStatusId = todoStatus.id
}

const order = await incrCache(counterKey)
const result = await mdTaskAdd({
title,
cover: null,
order: order,
startDate: null,
dueDate: dueDate || null,
plannedStartDate: dueDate || null,
plannedDueDate: dueDate || null,
assigneeIds,
desc,
done,
fileIds: [],
projectId,
priority,
taskStatusId: taskStatusId,
tagIds: [],
visionId: visionId || null,
parentTaskId: null,
taskPoint: null,
createdBy: id,
createdAt: new Date(),
updatedAt: null,
updatedBy: null,
progress
const taskService = new TaskService()
const result = await taskService.createNewTask({
uid: req.authen.id,
body: req.body
})

activityService.createTask({
id: result.id,
userId: id
})

const processes = []

// delete todo counter
if (assigneeIds && assigneeIds[0]) {
processes.push(deleteTodoCounter([assigneeIds[0], projectId]))
}

// delete all cached tasks
processes.push(findNDelCaches(key))

// run all process
await Promise.allSettled(processes)

if (result.assigneeIds && result.assigneeIds.length) {
// if created user and assigned user are the same person
// do not send notification
if (result.assigneeIds[0] !== id) {
const project = await mdProjectGet(result.projectId)
const taskLink = genFrontendUrl(
`${project.organizationId}/project/${projectId}?mode=task&taskId=${result.id}`
)

notifyToWebUsers(result.assigneeIds, {
title: 'Got a new task',
body: `${result.title}`,
deep_link: taskLink
})
}
}

res.json({ status: 200, data: result })
} catch (error) {
console.log(error)
res.json({ status: 500, error })
res.status(500).send(error)
}
})

Expand Down Expand Up @@ -581,9 +499,13 @@ router.put('/project/task', async (req: AuthRequest, res) => {
await Promise.allSettled(processes)

const getWatchers = async () => {
const watchers = await projectSettingRepo.getAllNotifySettings(result.projectId)
const watchers = await projectSettingRepo.getAllNotifySettings(
result.projectId
)
// merge watchers and make sure that do not send it to user who updated this task
const watcherList = [...result.assigneeIds, ...watchers].filter(uid => uid !== userId)
const watcherList = [...result.assigneeIds, ...watchers].filter(
uid => uid !== userId
)
return watcherList
}

Expand Down Expand Up @@ -617,7 +539,6 @@ router.put('/project/task', async (req: AuthRequest, res) => {
body: `From ${oldProgress} => ${result.progress} on "${result.title}"`,
deep_link: taskLink
})

}

res.json({ status: 200, data: result })
Expand Down
49 changes: 48 additions & 1 deletion packages/be-gateway/src/routes/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,14 @@ import {
Res
} from '../../core'
import { CounterType } from '@prisma/client'
import { CKEY, incrCache, setCache } from '../../lib/redis'
import {
CKEY,
delCache,
findCache,
incrCache,
setCache,
setJSONCache
} from '../../lib/redis'

import { TaskQueue, getTaskQueueInstance } from '../../queues'

Expand All @@ -22,6 +29,46 @@ export class TestController extends BaseController {
this.taskQueue = getTaskQueueInstance()
}

calculateSecondBetween2Date() {
const d1 = new Date()
const d2 = new Date(
d1.getFullYear(),
d1.getMonth(),
d1.getDate(),
d1.getHours(),
d1.getMinutes() + 2
)

return (d2.getTime() - d1.getTime()) / 1000
}

@Get('/hello')
async sayHello() {
const { taskId } = this.req.query as { taskId: string }
console.log('hello to test/ api ')

console.log(
'calculate second between 2 dates',
this.calculateSecondBetween2Date()
)

const key = [`remind-${taskId}-24-03-14-14:45`]
const result = await findCache(key, true)

console.log('result:', result)

if (!result.length) {
await setJSONCache(key, {
title: 'Just 15p to this meeting'
})
} else {
console.log('delete cache')
delCache(key)
}

return 1111
}

@Get('/bullmq')
async runQueue() {
// await this.taskQueue.addJob('name', {
Expand Down
Loading

0 comments on commit 38dfb48

Please sign in to comment.