Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //put interpreter into strict mode
- "use strict";
- //require the express and morgan packages
- const express = require("express");
- const morgan = require("morgan");
- const mongo = require("mongodb");
- const ObjectId = require("mongodb").ObjectId;
- var MongoClient = require("mongodb").MongoClient;
- var url = "mongodb://mongodb:27017/";
- const contentType = "Content-Type";
- const appJson = "application/json";
- const amqp = require('amqplib/callback_api')
- MongoClient.connect(url, function (err, db) {
- if (err) throw err;
- let dbo = db.db("mydb");
- console.log("Database created!");
- dbo.createCollection("channels", function (err, res) {
- console.log("Channel Collection created!");
- });
- dbo.createCollection("messages", function (err, res) {
- console.log("Messages Collection created!");
- });
- const general = {
- name: "general",
- createdAt: new Date()
- };
- dbo.collection("channels").update({ name: "general" }, general, { upsert: true });
- });
- //create a new express application
- const app = express();
- //get ADDR environment variable,
- //defaulting to ":80"
- const addr = process.env.NODE_ADDR || ":80";
- //split host and port using destructuring
- const [host, port] = addr.split(":");
- //add JSON request body parsing middleware
- app.use(express.json());
- //add the request logging middleware
- app.use(morgan("dev"));
- async function connectToRabbit() {
- await amqp.connect("amqp://" + process.env.RABBITMQADDR + ":5672/", async (err, conn) => {
- await conn.createChannel(function (err, ch) {
- var q = process.env.RABBITMQADDR;
- ch.assertQueue(q, { durable: false });
- channel = ch;
- });
- });
- }
- let channel;
- connectToRabbit();
- function getChannel() {
- return channel;
- }
- app
- .route("/v1/channels")
- .get((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length == 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- let reqUserID = JSON.parse(JSON.stringify(req.header("X-User"))).id;
- MongoClient.connect(url, function (err, db) {
- if (err) throw err;
- let dbo = db.db("mydb");
- dbo
- .collection("channels")
- .find(req.query.startsWith && { name: new RegExp("^" + req.query.startsWith) }, { creator: reqUserID })
- .toArray(function (err, result) {
- if (err) throw err;
- res.status(200);
- res.set(contentType, appJson);
- res.json(result);
- db.close();
- return;
- });
- });
- })
- .post((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length == 0) {
- res.setHeader('Content-Type', 'text/plain')
- res.status(401).send("Unauthorized");
- return;
- }
- let reqUserID = JSON.parse(req.header("X-User")).id;
- res.set("Content-Type", "application/json");
- var myobj = req.body;
- if (!myobj.name) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Channel name is required");
- return;
- } else {
- MongoClient.connect(url, async function (err, db) {
- if (err) throw err;
- let dbo = db.db("mydb");
- if (myobj.name == null) myobj.name = "";
- if (myobj.description == null) myobj.description = "";
- if (myobj.private == null) myobj.private = false;
- myobj.members == null
- ? (myobj.members = [{ id: reqUserID }])
- : (myobj.members = [{ id: reqUserID }].concat(myobj.members));
- myobj.createdAt = new Date();
- myobj.creator = JSON.parse(req.header("X-User"));
- myobj.editedAt = null;
- const duplicatechannel = await dbo.collection("channels").findOne({ name: myobj.name });
- if (duplicatechannel) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(400).send("Duplicate channel");
- return;
- }
- dbo.collection("channels").insertOne(myobj, function (err, result) {
- if (err) throw err;
- let channelMembers = [];
- myobj.members && myobj.private && myobj.members.forEach(member => {
- channelMembers.push(member.id);
- });
- console.log("MYOBJ---------------", myobj);
- myobj.id = myobj._id;
- console.log("MYOBJ---------------", myobj);
- const event = {
- type: "channel-new",
- channel: myobj,
- userIDs: channelMembers
- };
- getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
- res.status(201);
- res.set(contentType, appJson);
- // myobj.id = myobj._id;
- res.json(myobj);
- db.close();
- return;
- });
- });
- }
- })
- .all((req, res) => {
- res.setHeader('Content-Type', 'text/plain');
- res.status(405).send('method not allowed');
- return
- });
- app
- .route("/v1/channels/:channelID")
- .get((req, res) => {
- res.set(contentType, appJson);
- if (!req.get("X-User") || req.get("X-User").length == 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- if (req.params.channelID.length != 24) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Invalid channel ID");
- return;
- }
- let newChannelID = new mongo.ObjectId(req.params.channelID);
- let reqUserID = JSON.parse(req.header("X-User")).id;
- MongoClient.connect(url, function (err, db) {
- if (err) throw err;
- let dbo = db.db("mydb");
- dbo.collection("channels").findOne(
- {
- _id: newChannelID
- },
- function (err, result) {
- if (err) throw err;
- let memberArr = function () {
- for (let x of result.members) {
- if (x.id == reqUserID) {
- return true;
- }
- }
- return false;
- };
- console.log("result", result);
- if (result && result.private == true && !memberArr()) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Current user is not member of channel " + newChannelID);
- return;
- } else {
- // console.log("result", result);
- dbo
- .collection("messages")
- .find({
- channelID: newChannelID
- })
- .limit(100)
- .toArray(function (err, result2) {
- if (err) throw err;
- const result3 = [];
- result2.forEach((r) => {
- r.id = r._id; result3.push(r)
- });
- res.status(200);
- res.json(result3)
- db.close();
- return
- });
- db.close();
- }
- }
- );
- });
- })
- .post((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length == 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- let reqUserID = JSON.parse(req.header("X-User")).id;
- if (req.params.channelID.length != 24) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Invalid channel ID");
- return;
- }
- let channelID = new mongo.ObjectId(req.params.channelID);
- MongoClient.connect(url, function (err, db) {
- if (err) throw err;
- let dbo = db.db("mydb");
- dbo.collection("channels").findOne(
- {
- _id: channelID
- },
- function (err, result) {
- if (err) throw err;
- let memberArr = function () {
- for (let x of result.members) {
- if (x.id == reqUserID) {
- return true;
- }
- }
- return false;
- };
- if (result == null || (result.private == true && !memberArr())) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Current user is not member of channel " + channelID);
- return;
- } else {
- let msgObj = req.body;
- msgObj.body = req.body.body;
- msgObj.channelID = channelID;
- msgObj.createdAt = new Date();
- msgObj.creator = JSON.parse(req.get("X-User"));
- msgObj.editedAt = null;
- dbo.collection("messages").insertOne(msgObj, async function (err, result) {
- if (err) throw err;
- let channelMembers = [];
- const foundChannel = await dbo.collection("channel").findOne({ _id: msgObj.channelID })
- if (foundChannel) {
- foundChannel.members && foundChannel.private && foundChannel.members.forEach(member => {
- channelMembers.push(member.id);
- });
- }
- const event = {
- type: "message-new",
- message: msgObj,
- userIDs: channelMembers
- };
- getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
- res.status(201);
- res.set("Content-Type", "application/json");
- msgObj.id = msgObj._id;
- console.log("MSGOBJ---------------", msgObj);
- res.json(msgObj);
- db.close();
- return;
- });
- }
- }
- );
- });
- })
- .patch((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length == 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- if (req.params.channelID.length != 24) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Invalid channel ID");
- return;
- }
- let channelID = new mongo.ObjectId(req.params.channelID);
- let reqUserID = JSON.parse(req.header("X-User")).id;
- let reqBody = req.body;
- MongoClient.connect(url, async (err, db) => {
- if (err) throw err;
- let dbo = db.db("mydb");
- const result = await dbo.collection("channels").findOne({ _id: channelID });
- if (reqUserID != result.creator.id) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Unauthorized user or channel does not exist");
- return;
- } else {
- dbo
- .collection("channels")
- .findOneAndUpdate(
- { _id: channelID },
- { $set: { name: reqBody.name, description: reqBody.description, editedAt: new Date() } },
- { returnOriginal: false },
- (err, document) => {
- if (err) throw err;
- let result = document.value;
- let channelMembers = [];
- result.members && result.private && result.members.forEach(member => {
- channelMembers.push(member.id);
- });
- const event = {
- type: "channel-update",
- channel: result,
- userIDs: channelMembers
- };
- console.log("json stringify result", JSON.stringify(result));
- console.log("event stringify", JSON.stringify(event))
- getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
- res.setHeader('Content-Type', 'application/json');
- res.status(200);
- result.id = result._id;
- console.log("result", result)
- console.log("@@@@@@@@@2@@@", typeof result)
- res.json(result);
- db.close();
- }
- );
- }
- });
- })
- .delete((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length == 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- if (req.params.channelID.length != 24) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Invalid channel ID");
- return;
- }
- let channelID = new mongo.ObjectId(req.params.channelID);
- let reqUserID = JSON.parse(req.header("X-User")).id;
- MongoClient.connect(url, async (err, db) => {
- if (err) throw err;
- let dbo = db.db("mydb");
- const result = await dbo.collection("channels").findOne({ _id: channelID });
- console.log("REQUSERID-----------------", req.header("X-User"))
- console.log("REQUSERID-----------------", reqUserID);
- console.log("RESULTCREATOR-----------------", result.creator.id);
- if (reqUserID != result.creator.id) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Unauthorized user or channel does not exist");
- return;
- } else {
- const foundChannel = await dbo.collection("channels").findOne({ _id: channelID });
- await dbo.collection("channels").remove({ _id: channelID });
- dbo.collection("messages").deleteMany({ channelID: channelID }, async (err, document) => {
- if (err) throw err;
- let channelMembers = [];
- if (foundChannel) {
- foundChannel.members.forEach(member => {
- channelMembers.push(member.id);
- });
- }
- const event = {
- type: "channel-delete",
- channelID: foundChannel.id,
- userIDs: channelMembers
- };
- getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
- res.setHeader('Content-Type', 'text/plain');
- res.status(200).send(`Channel with id "${channelID}" was successfuly deleted!"`);
- db.close();
- return
- });
- }
- });
- })
- .all((req, res) => {
- res.setHeader('Content-Type', 'text/plain')
- res.status(405).send('method not allowed')
- return
- });
- app
- .route("/v1/channels/:channelID/members")
- .post((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length === 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- if (req.params.channelID.length != 24) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Invalid channel ID");
- return;
- }
- let channelID = new mongo.ObjectId(req.params.channelID);
- const currentUser = JSON.parse(req.header("X-User"));
- const userBody = req.body;
- MongoClient.connect(url, async (err, db) => {
- if (err) throw err;
- let dbo = db.db("mydb");
- const result = await dbo.collection("channels").findOne({ _id: channelID });
- if (!result || JSON.stringify(result.creator) !== JSON.stringify(currentUser)) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Unauthorized user or channelID does not exist");
- return;
- } else {
- dbo
- .collection("channels")
- .findOneAndUpdate(
- { _id: channelID },
- { $push: { members: userBody } },
- { returnOriginal: false },
- (err, document) => {
- if (err) throw err;
- const result = document.value;
- res.setHeader('Content-Type', 'text/plain');
- res.status(201).send(`User with id "${userBody.id}" was added as a member to channel "${channelID}"`);
- db.close();
- return
- }
- );
- }
- });
- })
- .delete((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length === 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- if (req.params.channelID.length != 24) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Invalid channel ID");
- return;
- }
- let channelID = new mongo.ObjectId(req.params.channelID);
- const currentUser = JSON.parse(req.header("X-User"));
- const userBody = req.body;
- MongoClient.connect(url, async (err, db) => {
- if (err) throw err;
- let dbo = db.db("mydb");
- const result = await dbo.collection("channels").findOne({ _id: channelID });
- if (!result || JSON.stringify(result.creator) !== JSON.stringify(currentUser)) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Unauthorized user or channelID does not exist");
- return;
- } else {
- dbo
- .collection("channels")
- .findOneAndUpdate(
- { _id: channelID },
- { $pull: { members: userBody } },
- { returnOriginal: false },
- (err, document) => {
- if (err) throw err;
- res.setHeader('Content-Type', 'text/plain');
- res.status(201).send(`User with id "${userBody.id}" was removed as a member to channel "${channelID}"`);
- db.close();
- return
- }
- );
- }
- });
- })
- .all((req, res) => {
- res.setHeader('Content-Type', 'text/plain')
- res.status(405).send('method not allowed')
- return
- });
- app
- .route("/v1/messages/:messageID")
- .patch((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length == 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- if (req.params.messageID.length != 24) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Invalid message ID");
- return;
- }
- let messageID = new mongo.ObjectId(req.params.messageID);
- const user = JSON.parse(req.header("X-User"));
- console.log("user", user)
- MongoClient.connect(url, async function (err, db) {
- if (err) throw err;
- let dbo = db.db("mydb");
- const result = await dbo.collection("messages").findOne({ _id: messageID });
- console.log("msg result", result);
- if (user.id != result.creator.id) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Unauthorized user or messageID does not exist");
- return;
- } else {
- console.log("user in else", user)
- console.log("user in else", user._id)
- dbo
- .collection("messages")
- .findOneAndUpdate(
- { _id: messageID },
- { $set: { body: req.body.body, editedAt: new Date() } },
- { returnOriginal: false },
- async (err, document) => {
- if (err) throw err;
- let result = document.value;
- let channelMembers = [];
- const foundChannel = await dbo.collection("channels").findOne({ _id: result.channelID })
- foundChannel.members && foundChannel.private && foundChannel.members.forEach(member => {
- channelMembers.push(member.id);
- });
- const event = {
- type: "message-update",
- message: result,
- userIDs: channelMembers
- };
- getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
- res.setHeader('Content-Type', 'application/json');
- res.status(200);
- result.id = result._id;
- res.json(result);
- db.close();
- return
- }
- );
- }
- });
- })
- .delete((req, res) => {
- if (!req.get("X-User") || req.get("X-User").length == 0) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(401).send("Unauthorized");
- return;
- }
- console.log("--------------------", req.params)
- console.log("--------------------", req.params.messageID)
- if (req.params.messageID.length != 24) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Invalid message ID");
- return;
- }
- let messageID = new mongo.ObjectId(req.params.messageID);
- const currentUser = JSON.parse(req.header("X-User"));
- MongoClient.connect(url, async (err, db) => {
- if (err) throw err;
- let dbo = db.db("mydb");
- const result = await dbo.collection("messages").findOne({ _id: messageID });
- console.log("ID----------------------", result.creator.id);
- console.log("ID----------------------", currentUser.id);
- console.log("ID----------------------", currentUser);
- console.log("ID----------------------", result.creator);
- console.log("ID----------------------", typeof currentUser);
- console.log("ID----------------------", typeof result.creator);
- if (JSON.stringify(result.creator.id) != JSON.stringify(currentUser.id)) {
- res.setHeader('Content-Type', 'text/plain');
- res.status(403).send("Unauthorized user or messageID does not exist");
- return;
- } else {
- dbo.collection("messages").remove({ _id: messageID }, async (err, deleted) => {
- if (err) throw err;
- let channelMembers = [];
- const foundChannel = await dbo.collection("channels").findOne({ _id: result.channelID })
- foundChannel.members && foundChannel.private && foundChannel.members.forEach(member => {
- channelMembers.push(member.id);
- });
- const event = {
- type: "message-delete",
- messageID: result.id,
- userIDs: channelMembers
- };
- getChannel().sendToQueue(process.env.RABBITMQADDR, new Buffer(JSON.stringify(event)), { persistent: true });
- res.setHeader('Content-Type', 'text/plain');
- res.status(200).send(`Message with ID ${messageID} was successful deleted!`);
- return;
- });
- }
- });
- })
- .all((req, res) => {
- res.setHeader('Content-Type', 'text/plain')
- res.status(405).send('method not allowed')
- });
- //start the server listening on host:port
- app.listen(parseInt(port), () => {
- console.log(`server is listening at http://${addr}...`);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement