new api /api/user/:username/friends - get friends list

This commit is contained in:
Moon Patel
2023-06-27 20:31:47 +05:30
parent 02b302e2c8
commit 8e91427c1c
5 changed files with 33 additions and 8 deletions
+3 -1
View File
@@ -2,6 +2,7 @@ const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const authRoutes = require("./routes/auth");
const userRoutes = require("./routes/user");
const mongoose = require("mongoose");
mongoose
@@ -26,7 +27,7 @@ io.on("connection", (socket) => {
});
socket.on("play", (data) => {
console.log(data)
console.log(data);
let { fromRow, fromCol, toRow, toCol, room } = data;
fromRow = 7 - fromRow;
fromCol = 7 - fromCol;
@@ -53,6 +54,7 @@ app.use((req, res, next) => {
// app.use("/", (req, res, next) => res.send('Hello'));
app.use("/api/auth", authRoutes);
app.use("/api/user", userRoutes);
app.use((error, req, res, next) => {
const status = error.status || 500;
+15 -5
View File
@@ -21,10 +21,12 @@ const userSchema = new Schema(
lname: String,
location: String,
country: String,
friends: {
type: [ObjectId],
ref: "User",
},
friends: [
{
type: ObjectId,
ref: "User",
},
],
},
{
virtuals: {
@@ -34,7 +36,15 @@ const userSchema = new Schema(
},
},
},
methods: {
async getFriends() {
await this.populate("friends", "username");
console.log(this.friends);
return this.friends.map(friend => friend.username);
},
},
}
);
module.exports.User = mongoose.model("User", userSchema);
const User = mongoose.model("User", userSchema);
module.exports = { User };
+13 -1
View File
@@ -1 +1,13 @@
const express = require("express").Router();
const router = require("express").Router();
const { checkAuth } = require("../util/auth");
const { User } = require("../models/user");
router.get("/:username/friends", async (req, res, next) => {
const username = req.params.username;
const user = await User.findOne({username});
const friends = await user.getFriends();
return res.json({ success: true, friends });
});
module.exports = router;
+2 -1
View File
@@ -30,6 +30,7 @@ function checkAuthMiddleware(req, res, next) {
return next(new NotAuthError("Not authenticated."));
}
const authFragments = req.headers.authorization.split(" ");
console.log(authFragments);
if (authFragments.length !== 2) {
console.log("NOT AUTH. AUTH HEADER INVALID.");
@@ -38,7 +39,7 @@ function checkAuthMiddleware(req, res, next) {
const authToken = authFragments[1];
try {
const validatedToken = validateJSONToken(authToken);
req.token = validatedToken;
req.userid = validatedToken;
} catch (error) {
console.log("NOT AUTH. TOKEN INVALID.");
return next(new NotAuthError("Not authenticated."));
View File