Skip to content

Commit

Permalink
Merge pull request #89 from TeamHARA/feat/scheduler
Browse files Browse the repository at this point in the history
[FEAT] 지정된 시간에 푸시알림 보내기
  • Loading branch information
leGit-y authored Dec 12, 2023
2 parents eecf8b0 + 47f0bd2 commit b8458f8
Show file tree
Hide file tree
Showing 11 changed files with 321 additions and 11 deletions.
67 changes: 67 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"jsonwebtoken": "^9.0.1",
"jwks-rsa": "^3.1.0",
"moment": "^2.29.4",
"node-cron": "^3.0.3",
"prisma": "^4.16.2",
"swagger-cli": "^4.0.4",
"yamljs": "^0.3.0"
Expand All @@ -40,6 +41,7 @@
"@types/jest": "^29.5.2",
"@types/jsonwebtoken": "^9.0.2",
"@types/node": "^18.15.11",
"@types/node-cron": "^3.0.11",
"@types/supertest": "^2.0.12",
"@types/swagger-ui-express": "^4.1.3",
"@types/yamljs": "^0.2.31",
Expand Down
2 changes: 1 addition & 1 deletion prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ model worry {

model token {
user_id Int @id
refresh_token String @unique @db.VarChar(150)
refresh_token String? @db.VarChar(150)
device_token String?
user user @relation(fields: [user_id], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "token_user_id_fk")
}
8 changes: 8 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import globalExceptionHandler from "./common/error/handler";
import router from './router';
import swaggerUi from 'swagger-ui-express';
import YAML from 'yamljs';
import scheduler from './modules/scheduler';


class App {
public setup(): Express {
Expand All @@ -22,6 +24,12 @@ class App {
});

app.use(globalExceptionHandler);


scheduler.deadline_alarm_1.start();
// scheduler.deadline_alarm_2.start();
scheduler.deadline_alarm_3.start();

return app;
}
}
Expand Down
102 changes: 95 additions & 7 deletions src/controller/alarmController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import admin from '../modules/firebaseAdmin';
import { userService } from "../service";
import tokenService from "../service/tokenService";
import { alarm } from "../constants";
import moment from "moment";
import alarmService from "../service/alarmService";

const setFinishedAlarm = async(req: Request, res: Response, next: NextFunction) => {
try{
Expand Down Expand Up @@ -37,10 +39,6 @@ const setFinishedAlarm = async(req: Request, res: Response, next: NextFunction)
"contents": msg,
"deviceToken": token
}
// req.body.title = title;
// req.body.contents = msg;
// req.body.deviceToken = token;
// next();

pushAlarm(data,next);

Expand All @@ -49,16 +47,74 @@ const setFinishedAlarm = async(req: Request, res: Response, next: NextFunction)
}
}

const setDeadlineAlarm = async(req: Request, res: Response, next: NextFunction) => {
const setOnDeadlineAlarm = async() => {
try{
const today = moment().format('YYYY-MM-DD');
const deviceTokens = await alarmService.getUserListByDeadline(new Date(today));
if(!deviceTokens){
console.log("no device tokens");
return;
}

const data = {
"title": alarm.DEADLINE_ALARM_TITLE,
"contents": alarm.ON_DEADLINE_ALARM,
"deviceTokens": deviceTokens
}

await pushAlarmToMany(data);

}catch (error) {
next(error);

}
}


const setBeforeDeadlineAlarm = async() => {
try{
const deadline = moment().add(3,"days").format('YYYY-MM-DD');
const deviceTokens = await alarmService.getUserListByDeadline(new Date(deadline));
if(!deviceTokens){
console.log("no device tokens");
return;
}

const data = {
"title": alarm.DEADLINE_ALARM_TITLE,
"contents": alarm.BEFORE_DEADLINE_ALARM,
"deviceTokens": deviceTokens
}

await pushAlarmToMany(data);

}catch (error) {

}
}

const setNoDeadlineAlarm = async() => {
try{
const createdAt = moment().subtract(30,"days").format('YYYY-MM-DD');
const deviceTokens = await alarmService.getUserListWithNoDeadline(createdAt);
if(!deviceTokens){
console.log("no device tokens");
return;
}

const data = {
"title": alarm.NO_DEADLINE_ALARM_TITLE,
"contents": alarm.NO_DEADLINE_ALARM,
"deviceTokens": deviceTokens
}

await pushAlarmToMany(data);

}catch (error) {

}
}


const pushAlarm = (data: any, next: NextFunction) => {
try{
const { deviceToken, title, contents } = data;
Expand Down Expand Up @@ -87,8 +143,40 @@ const pushAlarm = (data: any, next: NextFunction) => {

}

const pushAlarmToMany = async (data: any) => {
try{
const { deviceTokens, title, contents } = data;


let message = {
notification: {
title: title,
body: contents,
},
tokens: deviceTokens,
};

await admin
.messaging()
.sendMulticast(message)
.then(function (response:Response) {
console.log('Successfully sent messages');
// return res.status(200).json({success : true})
})
.catch(function (err:Error) {
console.log('Error Sending message!!! : ', err)
// return res.status(400).json({success : false})
});
} catch (error) {
console.log(error);
}

}

export default{
setFinishedAlarm,
setDeadlineAlarm,
setOnDeadlineAlarm,
setBeforeDeadlineAlarm,
setNoDeadlineAlarm,
pushAlarm
}
20 changes: 20 additions & 0 deletions src/modules/scheduler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import cron from 'node-cron';
import alarmController from '../controller/alarmController';

const option = {
scheduled: true,
timezone: "Asia/Seoul"
}
// 데드라인 3일 전 + 고민 작성 30일 후 : 오후 8시
const deadline_alarm_1 = cron.schedule('00 20 * * *', alarmController.setBeforeDeadlineAlarm, option);
const deadline_alarm_2 = cron.schedule('00 20 * * *', alarmController.setNoDeadlineAlarm, option);


// 데드라인 당일 알람 : 낮 12시
const deadline_alarm_3 = cron.schedule('00 12 * * *', alarmController.setOnDeadlineAlarm, option);

export default{
deadline_alarm_1,
deadline_alarm_2,
deadline_alarm_3
}
12 changes: 12 additions & 0 deletions src/repository/tokenRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,17 @@ const findIdByRefreshToken = async (refreshToken: string) => {
});
};

const findDeviceTokenListByIds = async (userId: number[]) => {
return await prisma.token.findMany({
select: {
device_token:true
},
where: {
user_id: { in: userId },
}
});
};

const updateTokenById = async (userId: number, refreshToken: string, deviceToken: string) => {
return await prisma.token.update({
where: {
Expand Down Expand Up @@ -73,6 +84,7 @@ export default {
findRefreshTokenById,
findDeviceTokenById,
findIdByRefreshToken,
findDeviceTokenListByIds,
updateTokenById,
disableRefreshTokenById

Expand Down
Loading

0 comments on commit b8458f8

Please sign in to comment.