Skip to content

Commit

Permalink
Merge pull request #10 from HUNG-rushb/noti
Browse files Browse the repository at this point in the history
Noti
  • Loading branch information
HUNG-rushb authored Nov 22, 2023
2 parents 6285e5e + d512178 commit 04e866a
Show file tree
Hide file tree
Showing 14 changed files with 1,822 additions and 258 deletions.
1,872 changes: 1,620 additions & 252 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"firebase-admin": "^11.11.0",
"graphql": "^16.8.1",
"graphql-subscriptions": "^2.0.0",
"graphql-tag": "^2.12.6",
Expand All @@ -61,8 +62,8 @@
"@types/jimp": "^0.2.28",
"@types/uuid": "^9.0.5",
"babel-loader": "^9.1.3",
"eslint": "^8.53.0",
"copy-webpack-plugin": "^11.0.0",
"eslint": "^8.53.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.1",
"nodemon": "^3.0.1",
Expand Down
Empty file.
1 change: 0 additions & 1 deletion src/Type_Definitions/Message_Message.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ const messageDefs = gql`
createMessage(data: CreateMessageInput!): Message!
deleteMessage(data: DeleteMessageInput!): Message!
deleteAllMessage: DeleteAllReturnType!
# updateReport(data: UpdateReportInput!): Report!
}
input CreateMessageInput {
Expand Down
5 changes: 5 additions & 0 deletions src/Type_Definitions/Story_Story.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ const storyDefs = gql`
allStories: [Story]!
storyInfo(data: StoryInfoInput!): Story!
getNewStories(limit: Int, after: String): StoryConnection!
getAllUserStories(
userId: String
currentUserId: String
after: String
): StoryConnection!
}
type StoryConnection {
Expand Down
8 changes: 8 additions & 0 deletions src/Type_Definitions/User_User.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ const userDefs = gql`
limit: Int
after: String
): UserPagination!
getAllUserLeaderboard: [User]!
getUserFollowingLeaderBoard(data: UserFollowingLeaderInput!): [User]!
}
type UserPagination {
Expand All @@ -38,6 +42,10 @@ const userDefs = gql`
userId: ID!
}
input UserFollowingLeaderInput {
userId: ID!
}
# _______________________________________________________
# _______________________________________________________
Expand Down
16 changes: 16 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,19 @@ export const DEFAULT_DEFINED_SKILL_LIST = [
'Wedding',
'White Balance',
];

export const googleApplicationCredentials = {
type: 'service_account',
project_id: 'noti-flens',
private_key_id: 'd5b516cd19b60c188144258820df3c2644fe53b2',
private_key:
'-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCf6WjHA69eVx+U\n+BUv58rtSGurlHZqFbCbjBMwE432veLIAFF4TOc0ReG5KcVaKa4lNOBD/c72T6bc\nnDey/Z+iK1bohvDaN35tbNBnyG971QsPDyF7HTADXlTT+ALKqxb66odkFwuGLQ+Y\nqJiKD8BZps94yQ56VoI2VFW6FATG/j38CiGZ451Fg+aFPVA7cN7GwDKfkXWhjR5i\nS+AigJGjn9A+sGwC3GRIB9t2oEuKQEGcTRDhVUnuCBqmTcaj17e51M13dGO/47jg\ndgWNc/Ne3nvPtwt2nvByi6kYGoxnYBL1QxxP1VrCDNVHVnUWVcE6wWDx97KEZtHc\nnfyLUhaJAgMBAAECggEABC5UnHt2rtdFTp5L44RCdIDDu+k2TWDCzNZVPBkOyag+\nUS9c8fHEy8OV+sLiU5CqanOe93gf3KXJfZQiCq6B6XoLnCnHC1WPGypQqp39eDXi\nQ6MII5FoS3ZAbohZ/lWJ1MakApRtqzTrZvjlgBqYU1++pfBPzhgL8IK0+RgD5fX+\nMVUxRU4w8nEB5LvozYxSlF+sMiJfQxOaeT8R89R8Kv44kGnhFc6GrB7yRADVSaHy\npC0Ex++5Zq3NWKh2lWoKCSx5tdgcpbZDWC+tOMg+Vypx+b+kMIcIAQoheFY6BMfU\nsYUQSrwjy+DA5W0VeDNRcnuX20kaRonOjcng9PDXHwKBgQDLMtVgwXzkZVPAOWCM\n4CF/UqfI9IS5gDvbXPZPHjRrQE4vVscsxrKGtMQYLgVIace0QleMt5PTY2VENy2w\n0T324OXiwqkm7nPCc3bKP1rhcL8YpFWfvMIgG1NOg5tld2i0FoFyHCSOB4mQ0jfJ\nfbxyi/3LIZnYSAXXw2BVMxTKRwKBgQDJdw1e1ooXud+SbVuZh9AjXVk+JXlwsJ0m\nge3G9zvwrmjtOumLxpFUU+aNlMkiSEBWDeO+b7/rKgR3y0KPmntbhWp9S92dgeTv\nj5SSj9cEH8GKu2Lsj1MipohISH8ZVzm1eIb6YtZLfkvfgn6G8z4mctkMYePbVdbq\neMsZvR2wrwKBgQCkMnmWbAPeE7svk63faKXo2wPWMTCnLWYxBtfKax/0oswLGNZt\n6koM7DmhSF7gewnzMcDJZva/VIxaKTR0s0CdJHLfYGmLmhhUwzT0jWmEzrS81t6R\n69f6VdplkZea0Hj9PUpwySkI1DJnoleOLFqBPXpiEM7epKSEC87mSha8tQKBgGaX\nPnLF80pDt8rb72JOW7o2hgR0ltPAzDXYwhmouphEaGAtuNIZytXTZ7s/QfE4M7Le\nndPTGjsJiX7rPbjc5OZlGSY25OKZS9iGGBVONCMAfNFFvQlTrvUdMpcEe9yOo296\nsdl9TTziUoa97+qOoV5463g3vQ1rN+bsnhg8Sos3AoGBAI+od/8B4PUNbvSqX0o0\nsjkpuyMF0I+XWiozjeNk/MIAB0agXB/ZU28CUHiQSauosqMv9WexUatoU+4QvXm+\nmtPRu9n6kYHCC/WJoGInWn4BrLsy057ktVI1YgIMIEemEII+ZnpJo8822JPeefM3\nm7QYkQn9FDjoRI4yKPmpB7T4\n-----END PRIVATE KEY-----\n',
client_email: '[email protected]',
client_id: '100889841805636667459',
auth_uri: 'https://accounts.google.com/o/oauth2/auth',
token_uri: 'https://oauth2.googleapis.com/token',
auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',
client_x509_cert_url:
'https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-p9pt7%40noti-flens.iam.gserviceaccount.com',
universe_domain: 'googleapis.com',
};
15 changes: 15 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,25 @@ import express from 'express';
import http from 'http';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer';
import { makeExecutableSchema } from '@graphql-tools/schema';
// Websocket
import { WebSocketServer } from 'ws';
import { useServer } from 'graphql-ws/lib/use/ws';
import { PubSub } from 'graphql-subscriptions';

// Firebase notification
import admin from 'firebase-admin';
import { googleApplicationCredentials } from './constants.js';

admin.initializeApp({
credential: admin.credential.cert(googleApplicationCredentials),
databaseURL:
'https://noti-flens-default-rtdb.asia-southeast1.firebasedatabase.app',
});

export const firebaseMessaging = admin.messaging();
// console.log({ firebaseMessaging });

// Web socket
const pubsub = new PubSub();

export { pubsub };
Expand Down
27 changes: 27 additions & 0 deletions src/notify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// https://firebase.google.com/docs/cloud-messaging/send-message
import { firebaseMessaging } from './index.js';

export const sendNotificationToClient = (tokens, data, notification) => {
// Send a message to the devices corresponding to the provided
// registration tokens.
firebaseMessaging
.sendMulticast({ tokens, data, notification })
.then((response) => {
// Response is an object of the form { responses: [] }
const successes = response.responses.filter(
(r) => r.success === true,
).length;

const failures = response.responses.filter(
(r) => r.success === false,
).length;

console.log(
'Notifications sent:',
`${successes} successful, ${failures} failed`,
);
})
.catch((error) => {
console.log('Error sending message:', error);
});
};
2 changes: 1 addition & 1 deletion src/prisma/ERD.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 16 additions & 0 deletions src/resolvers/Mutation/post.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { prisma } from '../../prisma/database.js';
import { hashImage } from '../Common/hashImage.js';
import { sendNotificationToClient } from '../../notify.js';

const postMutation = {
createPost: async (parent, args, info) => {
Expand Down Expand Up @@ -40,6 +41,21 @@ const postMutation = {
},
},
});

sendNotificationToClient(
[
'eUW71E0j4VAwZdHuyjdnQd:APA91bFKKXAsu_RxExCsDDK7V0AaqvHF9tW51bUBBDUkbvtxHEe9DpnFMhUfvgwVSAoud89y1rHxpeeEesWZZ9hkqAkkEMoP-7ys6QjYekcLln-bnXvvWfdG2ISZGwLtIm0iVH526VLr',
],
{
title: 'New post',
body: 'New post',
},
{
title: 'New post',
body: 'New post',
post,
},
);
} catch (e) {
console.log(e);
throw e;
Expand Down
4 changes: 1 addition & 3 deletions src/resolvers/Query/POST.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,9 @@ const postQuery = {
};
},
getAllUserPosts: async (parent, args, info) => {
let nodes;
let a, nodes;
const after = args.after;

let a;

if (args.currentUserId === args.userId) {
a = await prisma.post.findMany({
where: {
Expand Down
82 changes: 82 additions & 0 deletions src/resolvers/Query/STORY.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,88 @@ const storyQuery = {
},
});
},
getAllUserStories: async (parent, args, info) => {
let a, nodes;
const after = args.after;

if (args.currentUserId === args.userId) {
a = await prisma.story.findMany({
where: {
userId: args.userId,
},
orderBy: {
createdAt: 'desc',
},
});
} else {
// console.log(2);
const follower = await prisma.follower.findUnique({
where: {
userId: args.userId,
},
});
// console.log({ follower });

if (follower.userFollower.includes(args.currentUserId)) {
// console.log(3);
a = await prisma.story.findMany({
where: {
userId: args.userId,
OR: [
{ storyViewStatus: 'PUBLIC' },
{ storyViewStatus: 'ONLY_FOLLOWERS' },
],
},
orderBy: {
createdAt: 'desc',
},
});
} else {
a = await prisma.story.findMany({
where: {
userId: args.userId,
storyViewStatus: 'PUBLIC',
},
orderBy: {
createdAt: 'desc',
},
});
}
}

if (!after) {
nodes = a.slice(0, 2).map((story) => ({
node: story,
cursor: story.id,
}));

// console.log({ nodes });
} else {
// console.log('in after');
const index = a.findIndex((story) => story.id === after);
nodes = a.slice(index + 1, index + 3).map((story) => ({
node: story,
cursor: story.id,
}));

console.log({ nodes });
}

const hasNextPage =
nodes.length === 0
? false
: nodes.slice(-1)[0].cursor !== a.slice(-1)[0].id;

return {
edges: nodes,
pageInfo: {
hasNextPage,
hasPreviousPage: after ? true : false,
startCursor: nodes.length === 0 ? '' : nodes[0].cursor,
endCursor: nodes.length === 0 ? '' : nodes.slice(-1)[0].cursor,
},
};
},
};

export default storyQuery;
29 changes: 29 additions & 0 deletions src/resolvers/Query/USER.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,35 @@ const userQuery = {
},
};
},
getAllUserLeaderboard: async (parent, args, info) => {
return await prisma.user.findMany({
where: {
isAdmin: 0,
},
take: 5,
orderBy: {
level: { currentLevel: 'desc' },
},
});
},
getUserFollowingLeaderBoard: async (parent, args, info) => {
const currentUser = await prisma.following.findUnique({
where: {
userId: args.data.userId,
},
});

return await prisma.user.findMany({
where: {
id: { in: currentUser.userFollowing },
isAdmin: 0,
},
take: 5,
orderBy: {
level: { currentLevel: 'desc' },
},
});
},
};

export default userQuery;

0 comments on commit 04e866a

Please sign in to comment.