Sunday, 29 December 2019

GET not returning sent message. Only inbox items

When a user sends a message, it generates a messageTrackingId. Right now it $unwinds the creatorName as a unique returned value in inbox. I want only one user entry. No duplicates of the same user. Currently though they can send multiple messages if the other user hasn't responded generating new messageTrackingIds as a result. How can I make the initial sent message appear in the inbox as well so that I can use that messageTrackingId instead of generating new ones? I've been stuck on this for awhile so I appreciate any help.

app.get

app.get("/api/messages", (req, res, next) => {
  query = {};
  inbox = false;
  messageId = false;
  if (req.query.recipientId) {
    query = { recipientId: req.query.recipientId };
    inbox = true;

    Messages.aggregate(
      // Pipeline
      [
        {
          $lookup: {
            from: "users", // other table name
            localField: "creator", // name of users table field
            foreignField: "_id", // name of userinfo table field
            as: "creatorName" // alias for userinfo table
          }
        },
        { $unwind: "$creatorName" },
        {
          $match: {
            recipientId: { $eq: req.query.recipientId }
          }
        },

        // Stage 1
        {
          $group: {
            _id: "$messageTrackingId",
            message: { $addToSet: "$message" },
            recipientId: { $addToSet: "$recipientId" },
            creator: { $addToSet: "$creator" },
            messageTrackingId: { $addToSet: "$messageTrackingId" },
            creatorName: { $addToSet: "$creatorName.instagramName" },
            creationDate: { $addToSet: "$creationDate" }
          }
        },

        // Stage 2
        {
          $project: {
            _id: 1,
            message: { $arrayElemAt: ["$message", 0] },
            recipientId: { $arrayElemAt: ["$recipientId", 0] },
            creator: { $arrayElemAt: ["$creator", 0] },
            messageTrackingId: { $arrayElemAt: ["$messageTrackingId", 0] },
            creatorName: { $arrayElemAt: ["$creatorName", 0] },
            creationDate: { $arrayElemAt: ["$creationDate", 0] }
          }
        }
      ]
    )
      //.populate('creator', 'instagramName')

      .then(documents => {
        if (res.subject === "Test") {
          console.log("Nice");
        }
        if (inbox === false && messageId === false) {
          res.status(200).json({
            message: "User's Sent Messages Retrieved!",
            posts: documents
          });
        }
        if (inbox === true) {
          res.status(200).json({
            message: "User's Inbox Retrieved!",
            posts: documents
          });
        }
        if (messageId === true) {
          res.status(200).json({
            message: "Message Chain Retrieved!",
            posts: documents
          });
        }
      });

    //   .exec((err, locations) => {
    //     if (err) throw err;
    //     console.log(locations);
    // });
  } else if (req.query.creator) {
    query = { creator: req.query.creator };
    inbox = false;
    Messages.find(query)
      .populate("creator", "instagramName")
      .then(documents => {
        if (inbox === false && messageId === false) {
          res.status(200).json({
            message: "User's Sent Messages Retrieved!",
            posts: documents
          });
        }
        if (inbox === true) {
          res.status(200).json({
            message: "User's Inbox Retrieved!",
            posts: documents
          });
        }
        if (messageId === true) {
          res.status(200).json({
            message: "Message Chain Retrieved!",
            posts: documents
          });
        }
      });
  } else if (req.query.messageId) {
    query = { messageTrackingId: req.query.messageId };
    console.log(req.query.messageId);
    messageId = true;
    console.log("MESSAGE ID IS TRUE");
    Messages.find(query)
      .populate("creator", "instagramName")
      .then(documents => {
        if (inbox === false && messageId === false) {
          res.status(200).json({
            message: "User's Sent Messages Retrieved!",
            posts: documents
          });
        }
        if (inbox === true) {
          res.status(200).json({
            message: "User's Inbox Retrieved!",
            posts: documents
          });
        }
        if (messageId === true) {
          res.status(200).json({
            message: "Message Chain Retrieved!",
            posts: documents
          });
        }
      });
  }
});

app.post

app.post("/api/messages", checkAuth, (req, res, next) => {
  console.log("Made It")
  messagingTrackingIDValue = "";

  const messaging = new Messages({
    creator: req.userData.userId,
    recipient: req.body.recipient,
    recipientId: req.body.recipientId,
    message: req.body.message,
    //message: req.body.message,
    messageTrackingId: req.body.messageTrackingId,
    creatorName: req.userData.username,
    creationDate: req.body.creationDate
  });

  //saves to database with mongoose
  messaging.save().then(result => {
    if (result.creator !== messaging.creator) {
    } else if (result.creator === req.userData.userId) {
    }
    console.log(result);
    res.status(201).json({
      message: "Message Sent Successfully!",
      postId: result._id
    });
  });
});

angular service

  sendMessage(
    recipient: string,
    message: string,
    creationDate: Date,
    recipientId: string,
    creatorName: string,
    messageTrackingId: string
  ) {
    const messaging: Messages = {
      id: null,
      recipient: recipient,
      message: message,
      creationDate: creationDate,
      creator: null,
      recipientId: recipientId,
      creatorName: creatorName,
      messageTrackingId: messageTrackingId
    };

    this.http
      .post<{ message: string; messagingId: string; creator: string }>(
        "http://localhost:3000/api/messages",
        messaging
      )
      .subscribe(responseData => {
        console.log(responseData);
        const id = responseData.messagingId;
        messaging.id = id;

        console.log("Message sent successfully!");

        //   window.location.reload();
        //  this.posts.push();
        //  this.postsUpdated.next([...this.posts]);
      });
  }




  replyToMessage(
    recipient: string,
    message: string,
    creationDate: Date,
    recipientId: string,
    creatorName: string,
    messageTrackingId: string
  ) {
    const messaging: Messages = {
      id: null,
      recipient: recipient,
      message: message,
      creationDate: creationDate,
      creator: null,
      recipientId: recipientId,
      creatorName: creatorName,
      messageTrackingId: messageTrackingId
    };

    this.http
      .post<{ message: string; messagingId: string; creator: string }>(
        "http://localhost:3000/api/messages",
        messaging
      )
      .subscribe(responseData => {
        console.log(responseData);
        const id = responseData.messagingId;
        messaging.id = id;

        console.log("Message sent successfully!");
      });
  }







  getMessages(recipientId: string) {
    return this.http
      .get<{
        message: string;
        posts: any;
        maxPosts: number;
        messageList: string;
      }>("http://localhost:3000/api/messages?recipientId=" + recipientId)
      .pipe(
        map(retrievedData => {
          return {
            posts: retrievedData.posts.map(post => {
              return {
                creator: post.creator,
                recipientId: post.recipientId,
                creationDate: post.creationDate,
                messageTrackingId: post.messageTrackingId,
                creatorName: post.creatorName,
                id: post._id
              };
            }),
            maxPosts: retrievedData.maxPosts
          };
        })
      );
  }

Here's an example of the recipient replying to message so sender gets messageTrackingId to use

First message and then reply message. Since the recipient replied, the sender has the messageTrackingId to use for next message to same user.

Made It
{ _id: 5e0674ddd55aae5294370870,
  creator: 5df0014e25ee451beccf588a,
  recipient: 'joe',
  recipientId: '5df00d08c713f722909c99c1',
  message: 'This is the initial message',
  messageTrackingId: '3cb3f5bb-5e17-49a7-8aca-4a61ddd1d847',
  creatorName: 'andy',
  creationDate: 2019-12-27T21:17:17.155Z,
  __v: 0 }
Made It
{ _id: 5e067529d55aae5294370872,
  creator: 5df00d08c713f722909c99c1,
  recipient: 'andy',
  recipientId: '5df0014e25ee451beccf588a',
  message: 'This is the reply message',
  messageTrackingId: '3cb3f5bb-5e17-49a7-8aca-4a61ddd1d847',
  creatorName: 'joe',
  creationDate: 2019-12-27T21:18:33.947Z,
  __v: 0 }

If recipient never replies and sender sends another message this happens:

Made It
{ _id: 5e06756bd55aae5294370873,
  creator: 5df00d08c713f722909c99c1,
  recipient: 'andy',
  recipientId: '5df0014e25ee451beccf588a',
  message: 'This is the first message',
  messageTrackingId: '2077a8e6-844c-4639-a4fa-7aee0b8beaf4',
  creatorName: 'joe',
  creationDate: 2019-12-27T21:19:39.217Z,
  __v: 0 }
Made It
{ _id: 5e06757cd55aae5294370874,
  creator: 5df00d08c713f722909c99c1,
  recipient: 'andy',
  recipientId: '5df0014e25ee451beccf588a',
  message: 'This is another message to same user.',
  messageTrackingId: 'feeb0e20-432e-4c9a-9f59-45913c194edc',
  creatorName: 'joe',
  creationDate: 2019-12-27T21:19:56.257Z,
  __v: 0 }


from GET not returning sent message. Only inbox items

No comments:

Post a Comment