Skip to content

Commit

Permalink
feat: Add cron job for sending today's diet notifications
Browse files Browse the repository at this point in the history
  • Loading branch information
suk-6 committed Jun 10, 2024
1 parent aa45598 commit 93c68bb
Showing 1 changed file with 32 additions and 5 deletions.
37 changes: 32 additions & 5 deletions src/neis/neis.service.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,46 @@
import { Injectable } from '@nestjs/common';
import { NeisMealModel } from 'src/models/neis';
import { FirebaseService } from '../firebase/firebase.service';
import { Cron } from '@nestjs/schedule';
import { ClassroomNo, Grade } from '../models/timetable';

@Injectable()
export class NeisService {
constructor(private readonly firebase: FirebaseService) {}

// Monday to Friday at 12:50 PM
@Cron('50 12 * * 1-5')
async _sendTodayDiet() {
const today = new Date();
const diet = await this.getDiet(today);
if (diet[0]) {
Object.keys(Grade).forEach((grade) => {
Object.keys(ClassroomNo).forEach((classroom) => {
this.firebase.sendNotificationByTopic(
`meal`,
`${Grade[grade]}-${ClassroomNo[classroom]}`,
diet[1],
diet[2],
{
title: diet[1],
body: diet[2],
type: 'meal',
click_action: 'meal',
},
);
});
});
}
}

async getDietInfo(dayString: string) {
const url = `https://open.neis.go.kr/hub/mealServiceDietInfo?KEY=${process.env.NEIS_API_KEY}&Type=json&ATPT_OFCDC_SC_CODE=J10&SD_SCHUL_CODE=7531328&MLSV_YMD=${dayString}`;
const response = await fetch(url, { cache: 'force-cache' });

return (await response.json()) satisfies NeisMealModel;
}

async getDiet(date: Date) {
async getDiet(date: Date): Promise<[boolean, string, string?]> {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
Expand All @@ -26,18 +53,18 @@ export class NeisService {
const dietInfo = (await this.getDietInfo(dayString))
.mealServiceDietInfo[1].row[0];

const diet = dietInfo.DDISH_NM.split('<br/>').map((item: string) =>
item.trim(),
const diet: string = dietInfo.DDISH_NM.split('<br/>').map(
(item: string) => item.trim(),
);
const kcal = dietInfo.CAL_INFO;
const kcal: string = dietInfo.CAL_INFO;

const result = [
true,
`${month}${day}일 (${dayOfWeek}) 급식`,
`${diet}\n\n${kcal}`,
];

return result;
return result as [boolean, string, string];
} catch (error) {
return [false, `${month}${day}일 (${dayOfWeek}) 급식`];
}
Expand Down

0 comments on commit 93c68bb

Please sign in to comment.