Skip to content

Commit

Permalink
Public fetch-user
Browse files Browse the repository at this point in the history
  • Loading branch information
katniny committed Dec 29, 2024
1 parent 0708bcd commit 8f8ab7e
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 19 deletions.
25 changes: 19 additions & 6 deletions functions/public/fetch-user.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,37 @@ const limiter = rateLimit({
});
app.use(limiter);

// allow only get requests
app.use((req, res, next) => {
if (req.method !== "GET") {
return res.status(405).send({ error: "Method not allowed. Only GET requests are allowed." });
}
next();
});

// define route
app.get("/", async (req, res) => {
try {
// get the uid from the query params
// get the username from the query params
const userId = req.query.id;
if (!userId) {
return res.status(400).send({
error: "User ID is required. If you're unsure how to get UID, please visit https://dev.transs.social/docs/enable-dev-mode"
error: "Username is required. If you attempted to use a UID, please use a username instead."
});
}

// fetch user data from realtime db
const userRef = db.ref(`users/${userId}`);
const snapshot = await userRef.once("value");
// fetch user uid from realtime db
const userRef = db.ref(`taken-usernames/${userId}/user`);
const user = await userRef.once("value");

if (!snapshot.exists()) {
if (!user.exists()) {
return res.status(404).send({ error: "User not found." });
}

// fetch user uid from realtime db
const userDataRef = db.ref(`users/${user.val()}`);
const snapshot = await userDataRef.once("value");

// send user data
res.set("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
Expand All @@ -69,6 +81,7 @@ app.get("/", async (req, res) => {
suspensionNotes: userData.suspensionNotes || {},
suspensionStatus: userData.suspensionStatus || null,
username: userData.username || null,
uid: user.val() || "Error occurred fetching UID",
};

return res.status(200).send(filteredUserData);
Expand Down
58 changes: 45 additions & 13 deletions testing/public/fetch-user.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,28 @@

<body>
<h1>Fetch User Data</h1>
<p>Allow either a username to fetch user data. A UID will be faster, but neither are truly slow, and usernames are easier to access.</p>
<p>^ Add username functionality tomorrow because it's currently just UID</p>
<p>Put in a username to fetch their public data.</p>
<p>~180ms per request (on average)</p>
<form id="fetchUserForm">
<label for="userId">User ID:</label>
<input type="text" id="userId" value="G6GaJr8vPpeVdvenAntjOFYlbwr2" required />
<label for="userId">Username:</label>
<input type="text" id="userId" value="katniny" required />

<br />
<br />

<label for="httpMethod">HTTP Method:</label>
<select name="" id="httpMethod">
<option value="GET">GET</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
</select>

<br />
<br />

<textarea id="requestBody" placeholder="Optional request body (JSON)" rows="5" cols="30"></textarea>

<button type="submit">Fetch</button>
</form>

Expand All @@ -22,21 +39,36 @@ <h2>Response:</h2>
</div>

<script>
// handle form submission
document.getElementById("fetchUserForm").addEventListener("submit", async function(event) {
document.getElementById("fetchUserForm").addEventListener("submit", async function (event) {
event.preventDefault();

const userId = document.getElementById("userId").value;

const httpMethod = document.getElementById("httpMethod").value;
const requestBody = document.getElementById("requestBody").value;

const url = `http://127.0.0.1:5001/chat-transsocial-test/us-central1/fetchUser?id=${userId}`;

const options = {
method: httpMethod,
headers: {
"Content-Type": "application/json",
},
};

// only add body if it's a method that supports it
if (httpMethod === "POST" || httpMethod === "PUT") {
options.body = requestBody ? requestBody : "{}";
}

try {
const response = await fetch(`http://127.0.0.1:5001/chat-transsocial-test/us-central1/fetchUser?id=${userId}`);

const response = await fetch(url, options);
if (!response.ok) {
throw new Error("Error: ", response.statusText);
throw new Error(`Error: ${response.statusText} (HTTP ${response.status})`);
}

const data = await response.json();

// display the user data or error message

document.getElementById("responseData").textContent = JSON.stringify(data, null, 2);
} catch (error) {
document.getElementById("responseData").textContent = `Failed to fetch data; ${error.message}`;
Expand Down

0 comments on commit 8f8ab7e

Please sign in to comment.