Last active
October 22, 2023 18:30
-
-
Save satomiichii/8f24d67aa940c20166ae9c2b088cc001 to your computer and use it in GitHub Desktop.
Subscribe route
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 router = require('express').Router() | |
const {User, Subscription} = require('../db/models') | |
module.exports = router | |
router.post('/:userId', async (req, res, next) => { | |
try { | |
const userId = req.params.userId | |
const data = req.body | |
//subscription object has 3 properties and the value of the 'keys' property is a nested object, so | |
//to store the value in PostgreSQL, it has to be stringified. | |
const subKeys = JSON.stringify(data.keys) | |
const user = await User.findByPk(userId) | |
if (user) { | |
//Only if the subscription doesn't exist in the server, create a new instance. | |
const [subscription] = await Subscription.findOrCreate({ | |
where: { | |
endpoint: data.endpoint, | |
keys: subKeys | |
}, | |
default: { | |
endpoint: data.endpoint, | |
expirationTime: data.expirationTime, | |
keys: subKeys | |
} | |
}) | |
//Make association between the subscription and the user. | |
subscription.setUser(user) | |
res.json(subscription) | |
} else { | |
res.status(401).send('User not found') | |
} | |
} catch (error) { | |
next(error) | |
} | |
}) | |
//delete all subscription data that associate with the user | |
router.delete('/:userId', async (req, res, next) => { | |
try { | |
await Subscription.destroy({where: {userId: req.params.userId}}) | |
} catch (error) { | |
next(error) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment