Skip to content

Instantly share code, notes, and snippets.

@edwilliams
Last active March 17, 2022 13:26
Show Gist options
  • Select an option

  • Save edwilliams/cde43c0a0437410d0f922c63991b6066 to your computer and use it in GitHub Desktop.

Select an option

Save edwilliams/cde43c0a0437410d0f922c63991b6066 to your computer and use it in GitHub Desktop.
// fixed version of https://javascript.plainenglish.io/introduction-to-redis-and-caching-with-node-js-using-upstash-88efbe39eea2
import express from 'express'
import mongoose from 'mongoose'
import bodyParser from 'body-parser'
import { createClient } from 'redis'
import { v4 as uuidv4 } from 'uuid'
const app = express()
app.use(bodyParser.json())
const client = createClient({
url: 'redis://:password@eu1-foo-bar-12345.upstash.io:12345',
})
client.on('error', err => console.log('Redis Client Error', err))
await client.connect()
mongoose.connect(
'mongodb://localhost:27017/',
{
dbName: 'notes',
useNewUrlParser: true,
useUnifiedTopology: true,
family: 4,
},
err => (err ? console.log(err) : console.log('Connected to database'))
)
const NoteSchema = new mongoose.Schema({
title: String,
note: String,
})
const Note = mongoose.model('Note', NoteSchema)
app.post('/api/notes', async (req, res, next) => {
const { title, note } = req.body
const _note = new Note({
title: title,
note: note,
})
_note.save((err, note) => {
if (err) {
return res.status(404).json(err)
}
const id = uuidv4()
const data = JSON.stringify(req.body)
try {
// todo: determine how to set a timestamp on the resource
// i.e. before time get redis, after get from mongo
await client.set(id, data)
return res.status(201).json({
message: 'Note has been saved',
data: req.body,
})
} catch (error) {
return res.status(400).json({
message: 'redis error',
})
}
})
})
const isCached = (req, res, next) => {
const { id } = req.params
const data = await client.set(id)
const reponse = JSON.parse(data)
return res.status(200).json(reponse)
next()
}
app.get('/api/notes/:id', isCached, (req, res) => {
const { id } = req.params
Note.findById(id, (err, note) => {
if (err) {
return res.status(404).json(err)
}
return res.status(200).json({
note: note,
})
})
})
app.listen(3000, () => console.log('Server running at port 3000'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment