Skip to content

Instantly share code, notes, and snippets.

View paulbreslin's full-sized avatar

Paul Breslin paulbreslin

View GitHub Profile
// API
router.get('/words', async (req, res) => {
const wordsRef = db.ref(`words`).once('value');
const usersRef = db.ref(`users`).once('value');
const values = await Promise.all([wordsRef, usersRef]);
const wordsVal = values[0].val();
const userVal = values[1].val();
res.sendStatus(200);
});
fetch('https://your-domain.com/api/words')
.then( response => response.json())
.then( json => {
// Handle data
})
.catch( error => {
// Error handling
});
// API
router.get('/words', async (req, res) => {
const {userId} = req.query;
const wordsSnapshot = await db.ref(`words/${userId}`).once('value');
// BAD
res.send(wordsSnapshot.val())
// GOOD
const response = Object.assign({}, snapshot.val());
const example = require('example-library');
const runDemo = async () => {
try {
const fistResponse = await example.firstAsyncRequest();
const secondResponse = await example.secondAsyncRequest(fistResponse);
const thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
}
catch (error) {
// Handle error
const example = require('example-library');
const runDemo = async () => {
const fistResponse = await example.firstAsyncRequest();
const secondResponse = await example.secondAsyncRequest(fistResponse);
const thirdAsyncRequest = await example.thirdAsyncRequest(secondResponse);
};
runDemo();
const example = require('example-library');
example.firstAsyncRequest()
.then( fistResponse => {
example.secondAsyncRequest(fistResponse)
.then( secondResponse => {
example.thirdAsyncRequest(secondResponse)
.then( thirdAsyncResponse => {
// Insanity continues
});
router.post('/words', async (req, res) => {
const {userId, word} = req.body;
const definition = await fetch(`https://words-api.com/definition/${word}`).json();
const wordData = {
word,
definition
};
db.ref(`words/${userId}`).set({wordData};
});
// API
router.get('/words', (req, res) => {
const {userId} = req.query;
db.ref(`words/${userId}`).once('value')
.then( snapshot => {
res.send(snapshot.val());
});
});
// API
router.get('/words', async (req, res) => {
const {userId} = req.query;
const wordsSnapshot = await db.ref(`words/${userId}`).once('value');
res.send(wordsSnapshot.val())
});
// API
router.post('/words', (req, res) => {
const {userId, word} = req.body;
db.ref(`words/${userId}`).push({word}, error => {
if (error) {
res.sendStatus(500);
// Log error to external service, e.g. Sentry
} else {
res.sendStatus(201);
}