-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFCM.ts
90 lines (84 loc) · 2.16 KB
/
FCM.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { GraphQLError } from "graphql";
import User from "../../../../Schema/User/User.model";
import { MutationFcmArgs } from "../../../Types/types";
import canSee from "../../../../helpers/canSee";
import { Types } from "mongoose";
require("dotenv").config();
const newFCM = async (
_,
{ id, FCM, action }: MutationFcmArgs,
{ admin, req }
) => {
try {
//authenticate the user the user
canSee(id, req.headers.authorization, "production");
switch (action) {
case "add":
await addUserFCM(id, FCM);
break;
case "remove":
await removeUserFCM(id, FCM);
break;
default:
throw new Error(
`action can not be ${action}, valid actions: "add" or "remove"`
);
}
return true;
/**
* this function insert the requested FCM into the user document
* and throws an error if it doesn't find the user
*
* @param id
* @param FCM
*
*/
async function addUserFCM(id: string, FCM: string) {
const response = await User.updateOne(
{ _id: id },
{
$push: {
FCMs: {
$each: [FCM],
$position: -1,
},
},
}
);
if (response.n === 0) {
throw new Error(`user with id ${id} does not exist`);
}
if (response.nModified === 0) {
throw new Error(`an error occured while adding the FCM`);
}
}
/**
* this function removes the requested FCM from the user document
* and throws an error if it doesn't find the user
*
* @param id
* @param FCM
*
*/
async function removeUserFCM(id: string, FCM: string) {
const response = await User.updateOne(
{ _id: id },
{
$pull: {
FCMs: FCM,
},
}
);
if (response.n === 0) {
throw new Error(`user with id ${id} does not exist`);
}
if (response.nModified === 0) {
throw new Error(`the FCM ${FCM} is already been deleted`);
}
}
} catch (e) {
console.log("error while creating a new fcm");
throw new GraphQLError(e.message);
}
};
export default newFCM;