Skip to content

Commit

Permalink
[ADD] 푸쉬 알림 API #15 #17
Browse files Browse the repository at this point in the history
  • Loading branch information
dltjdn committed Jul 20, 2022
1 parent d256f03 commit cc41a62
Show file tree
Hide file tree
Showing 10 changed files with 6,253 additions and 3,386 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ out
.nuxt
dist


firebase-admin.json

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
Expand Down
2,117 changes: 2,051 additions & 66 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,12 @@
"eslint-plugin-prettier": "^4.2.1",
"express": "^4.17.3",
"express-validator": "^6.14.2",
"firebase-admin": "^11.0.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^6.3.1",
"multer": "^1.4.4",
"multer-s3": "^2.10.0",
"node-schedule": "^2.1.0",
"winston": "^3.8.1"
}
}
3 changes: 2 additions & 1 deletion src/controllers/DailyController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,10 @@ const createDaily = async (req: Request, res: Response) => {
.status(statusCode.BAD_REQUEST)
.send(util.fail(statusCode.BAD_REQUEST, message.NULL_VALUE));
}

console.log(124321323124132);
const filmCreateDto: FilmCreateDto = req.body;
const userId = req.body.user.id;
console.log('유저 아이디', userId);

try {
const data = await DailyService.createDaily(userId, filmCreateDto);
Expand Down
17 changes: 17 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ import config from './config';
const app = express();
import connectDB from './loaders/db';
import routes from './routes';
import NotificationService from './services/NotificationService';
require('dotenv').config();
var nodeschedule = require('node-schedule');

connectDB();

Expand Down Expand Up @@ -34,6 +36,21 @@ app.use(function (
res.json({ error: res.locals.error });
});

// 푸쉬 알람
app.use(function (req: Request, res: Response) {
const userId = req.body.userId;

const capsuleRule = '0 0 8 * * *';
nodeschedule.scheduleJob(capsuleRule, function () {
NotificationService.postCapsuleNotice(userId);
});

const checkRule = '0 0 22 * * *';
nodeschedule.scheduleJob(checkRule, function () {
NotificationService.postCheckNotice(userId);
});
});

app
.listen(process.env.PORT, () => {
console.log(`
Expand Down
73 changes: 40 additions & 33 deletions src/loaders/db.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,44 @@
import mongoose from "mongoose";
import config from "../config";
import File from "../models/File";
import Film from "../models/Film";
import Keyword from "../models/Keyword";
import User from "../models/User";
import mongoose from 'mongoose';
import config from '../config';
import File from '../models/File';
import Film from '../models/Film';
import Keyword from '../models/Keyword';
import User from '../models/User';
import * as admin from 'firebase-admin';

var serviceAccount = require('../../firebase-admin.json');

const connectDB = async () => {
try {
await mongoose.connect(config.mongoURI);

mongoose.set('autoCreate', true);

User.createCollection().then(function (collection) {
console.log("User Collection is created!");
});

File.createCollection().then(function (collection) {
console.log("File Collection is created!");
});

Film.createCollection().then(function (collection) {
console.log("Film Collection is created!");
});

Keyword.createCollection().then(function (collection) {
console.log("Keyword Collection is created!");
});

console.log("Mongoose Connected ...");
} catch (err: any) {
console.error(err.message);
process.exit(1);
}
try {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount as admin.ServiceAccount),
});

await mongoose.connect(config.mongoURI);

mongoose.set('autoCreate', true);

User.createCollection().then(function (collection) {
console.log('User Collection is created!');
});

File.createCollection().then(function (collection) {
console.log('File Collection is created!');
});

Film.createCollection().then(function (collection) {
console.log('Film Collection is created!');
});

Keyword.createCollection().then(function (collection) {
console.log('Keyword Collection is created!');
});

console.log('Mongoose Connected ...');
} catch (err: any) {
console.error(err.message);
process.exit(1);
}
};

export default connectDB;
export default connectDB;
1 change: 1 addition & 0 deletions src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export default (req: Request, res: Response, next: NextFunction) => {
// 토큰 유무 검증
if (!token) {
// 토근없으면 접근 금지! 401
console.log(1243123);
return res
.status(statusCode.UNAUTHORIZED)
.send(util.fail(statusCode.UNAUTHORIZED, message.NULL_VALUE_TOKEN));
Expand Down
8 changes: 7 additions & 1 deletion src/services/DailyService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import User from '../models/User';
import { KeywordInfo } from '../interfaces/keyword/KeywordInfo';
import { FilmAllResponseDto } from '../interfaces/film/FilmAllResponseDto';
import { FilmResponseDto } from '../interfaces/film/FilmResponseDto';
import NotificationService from './NotificationService';

const getAllDaily = async (userId: string, year: string, month: string) => {
const daily: FilmAllResponseDto[] = [];
Expand Down Expand Up @@ -57,7 +58,6 @@ const getDaily = async (
} else {
rightFilmId = ' ';
}


const film = await Film.find(
{ writer: userId, _id: filmId },
Expand Down Expand Up @@ -238,6 +238,12 @@ const createDaily = async (
growthRate = 0;
}

// 푸쉬 알림
if ((count as number) % 10 === 0) {
NotificationService.postCapsuleNotice(userId);
}
//NotificationService.postCapsuleNotice(userId);

await User.findByIdAndUpdate(userId, {
count: count,
growthRate: growthRate,
Expand Down
128 changes: 128 additions & 0 deletions src/services/NotificationService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import User from '../models/User';
import * as admin from 'firebase-admin';
import mongoose from 'mongoose';
import Film from '../models/Film';

var nodeschedule = require('node-schedule');

const postCapsuleNotice = async (userId: string) => {
try {
const user = await User.find({ _id: userId }, { fcmToken: 1, count: 1 });
if (!user) {
return null;
}

const count = user[0].count;
if ((count as number) % 10 !== 0) {
return;
}

const fcmToken = user[0].fcmToken;

const message = {
android: {
data: {
title: 'happic',
body: '어제 떨어진 별똥별을 선물로 가져왔어!',
},
},
apns: {
payload: {
aps: {
contentAvailable: true,
alert: {
title: 'happic',
body: '어제 떨어진 별똥별을 선물로 가져왔어!',
},
},
},
},
token: fcmToken,
};

// 푸시알림 보내기
admin
.messaging()
.send(message)
.then(function (response: any) {
// const rule = '0 0 8 * * *';
// nodeschedule.scheduleJob(rule, function () {
// console.log('스케줄러 성공!');
// });
console.log('Successfully sent message: ', response);
})
.catch(function (err) {
console.log('Error Sending message!!! : ', err);
});
} catch (err) {
console.log(err);
throw err;
}
};

const postCheckNotice = async (userId: string) => {
const dayjs = require('dayjs');
try {
let films = await Film.find({ writer: userId }).sort({ createdAt: -1 });

const lastDate = dayjs(films[0].createdAt);
const lastDateFormat = lastDate.format('YY-MM-DD');

const nowDate = dayjs();
const nowDateFormat = nowDate.format('YY-MM-DD');

const todayPosted = lastDateFormat === nowDateFormat;

if (todayPosted == true) {
return;
}

const user = await User.find({ _id: userId }, { fcmToken: 1 });
if (!user) {
return null;
}
const fcmToken = user[0].fcmToken;
const message = {
android: {
data: {
title: 'happic',
body: '길잡이와 함께 해픽을 행복으로 채워보세요!',
},
},
apns: {
payload: {
aps: {
contentAvailable: true,
alert: {
title: 'happic',
body: '길잡이와 함께 해픽을 행복으로 채워보세요!',
},
},
},
},
token: fcmToken,
};
// 푸시알림 보내기
admin
.messaging()
.send(message)
.then(function (response: any) {
// const rule = '0 0 22 * * *';
// nodeschedule.scheduleJob(rule, function () {
// console.log('스케줄러 성공!');
// });
console.log('Successfully sent message: ', response);
})
.catch(function (err) {
console.log('Error Sending message!!! : ', err);
});
} catch (err) {
console.log(err);
throw err;
}
};

export default {
postCapsuleNotice,
postCheckNotice,
};
Loading

0 comments on commit cc41a62

Please sign in to comment.