Created
September 11, 2023 22:25
-
-
Save francium-lupe/84c82978a27cdedda13f9eee40900d33 to your computer and use it in GitHub Desktop.
Threads API endpoints for creating a new user, creating a thread, and retrieving a list of all threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const app = express(); | |
app.use(express.json()); | |
app.use(function(req, res, next) { | |
console.log(new Date(), req.method, req.url); | |
next(); | |
}); | |
const threads = []; | |
const users = []; | |
// Get all threads | |
app.get('/threads', function(req, res) { | |
res.json({ threads }); | |
}); | |
// Create a new user | |
app.post('/users', async function(req, res) { | |
if (req.body.id == null) { | |
throw new Error('User must have an id'); | |
} | |
if (users.find(user => user.id === req.body.id)) { | |
throw new Error(`Duplicate user id ${req.body.id}`); | |
} | |
const user = { | |
name: 'John Smith', | |
banned: false, | |
roles: [], | |
...req.body | |
}; | |
users.push(user); | |
res.json({ user }); | |
}); | |
// Create a new thread | |
app.post('/threads', async function(req, res) { | |
if (req.body.id == null) { | |
throw new Error('Thread must have an id'); | |
} | |
if (threads.find(thread => thread.id === req.body.id)) { | |
throw new Error(`Duplicate thread id ${req.body.id}`); | |
} | |
const thread = { | |
title: null, | |
comments: [], | |
locked: false, | |
userId: req.headers.authorization, | |
...req.body | |
}; | |
threads.push(thread); | |
res.json({ thread }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment