Skip to content
Snippets Groups Projects
Verified Commit cdf6e6d3 authored by Fredrik Fonn Hansen's avatar Fredrik Fonn Hansen :8ball:
Browse files

Create a simple users endpoint

parent 41c3f93f
No related branches found
No related tags found
1 merge request!3Resolve "Create a users endpoint"
node_modules/
npm-debug.log
dist/
\ No newline at end of file
dist/
keys/
.DS_Store
\ No newline at end of file
......@@ -8,6 +8,12 @@ Implemation in Typescript.
Package handler is Yarn.
## Setup
You must add a file in the following directory: `backend/keys/fb-key.json`
The key is login details to a Firebase service account, needed to access the database.
## How to run
Run the following commands in your terminal:
......
# API Documentation
### GET /user/
> - 204 No users found (DB is empty)
> - 200 List of user-id's
### GET /user/{id: string}
> - 404 User not found
> - 200 User
### GET /user/{username: string}
> - 404 User not found
> - 200 User
### POST /user/create/{id}
> - 409 User already exists
> - 201 User created
......@@ -5,7 +5,7 @@
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "tsc && node dist/index.js"
"start": "tsc && node dist/src/index.js"
},
"author": "",
"license": "ISC",
......@@ -13,5 +13,8 @@
"@types/express": "^4.17.17",
"express": "^4.18.2",
"typescript": "^4.9.5"
},
"dependencies": {
"firebase-admin": "^11.5.0"
}
}
import express from 'express';
import path from 'path';
const app = express();
const port = 3000;
// const cors = require('cors');
// app.use(cors());
// in testing, we don't want to cache the results
app.set('etag', false);
app.use((req, res, next) => {
res.setHeader('Cache-Control', 'no-store');
next();
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
......@@ -10,3 +21,66 @@ app.get('/', (req, res) => {
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
// establish connection to firebase
const admin = require('firebase-admin');
const serviceAccount = path.join(__dirname, '../..', 'keys', 'fb-key.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
// returns all the user-id's
app.get('/user', async (req, res) => {
const usersRef = admin.firestore().collection('users');
const querySnapshot = await usersRef.get();
if (querySnapshot.empty) {
res.status(204).send('No users found');
} else {
const userids = querySnapshot.docs.map((doc: { id: any; }) => doc.id);
res.status(200).send(userids);
}
});
// returns data of a specific user
app.get('/user/:idOrUsername', async (req, res) => {
const usersRef = admin.firestore().collection('users');
const snapshot = await usersRef.get();
const searchParam = req.params.idOrUsername;
const user = snapshot.docs.find((doc: { id: string; }) => doc.id === searchParam)
|| (await Promise.all(snapshot.docs.map(async (doc: { id: string; }) => {
const userSnapshot = await usersRef.doc(doc.id).get();
return userSnapshot.data().username === searchParam ? userSnapshot : null;
}))).find(Boolean);
if (user) {
res.status(200).send(user.data());
} else {
res.status(404).send('User not found');
}
});
// create new user
app.post('/user/create/:username', async (req, res) => {
const usersRef = admin.firestore().collection('users');
const querySnapshot = await usersRef.where('username', '==', req.params.username).get();
if (!querySnapshot.empty) {
res.status(409).send('User already exists');
} else {
const newUserRef = await usersRef.add({
username: req.params.username,
highscore: 0,
games: 0,
wins: 0,
losses: 0,
});
res.status(201).send(newUserRef.id);
}
});
\ No newline at end of file
......@@ -7,6 +7,10 @@
"strict": true,
"sourceMap": true
},
"include": ["src/**/*"]
"include": [
"src/**/*",
"types/**/*",
"keys/**/*"
]
}
\ No newline at end of file
type User = {
id: string;
username: string;
wins: number;
losses: number;
highscore: number;
};
\ No newline at end of file
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment