Clean up deleted user configs, sort by last modified
This commit is contained in:
parent
bb70d05226
commit
c9d73702c7
1 changed files with 24 additions and 3 deletions
|
|
@ -1,16 +1,37 @@
|
||||||
import { Request, Response } from 'express'
|
import { Request, Response } from 'express'
|
||||||
|
import moment from 'moment'
|
||||||
import ConfigSchema from '../db/config.schema'
|
import ConfigSchema from '../db/config.schema'
|
||||||
|
|
||||||
export const configGetHandler = async (req: Request, res: Response) => {
|
export const configGetHandler = async (req: Request, res: Response) => {
|
||||||
try {
|
try {
|
||||||
const configs = []
|
const configs = []
|
||||||
|
const newUserConfigs = []
|
||||||
|
|
||||||
for (const _id of req.user?.configs) {
|
for (const _id of req.user?.configs) {
|
||||||
const { name } = await ConfigSchema.findById(_id)
|
const conf = await ConfigSchema.findById(_id)
|
||||||
configs.push({ _id, name })
|
if (conf) {
|
||||||
|
configs.push({ _id, name: conf.name, upd: conf.updatedAt })
|
||||||
|
newUserConfigs.push(_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Update any deleted ones, this would be server-side but still.
|
||||||
|
if (req.user && req.user.configs.length != newUserConfigs.length) {
|
||||||
|
req.user.configs = newUserConfigs
|
||||||
|
await req.user.save()
|
||||||
}
|
}
|
||||||
|
|
||||||
return res.json(configs)
|
// Sort the configs by updated date
|
||||||
|
const sorted = configs.sort((a, b) => {
|
||||||
|
const dA = moment(a.upd)
|
||||||
|
const dB = moment(b.upd)
|
||||||
|
|
||||||
|
if (dA.diff(dB) === 0) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return dA.diff(dB) > 0 ? -1 : 1
|
||||||
|
})
|
||||||
|
|
||||||
|
return res.json(sorted)
|
||||||
} catch (ex) {
|
} catch (ex) {
|
||||||
console.error(ex)
|
console.error(ex)
|
||||||
return res.status(500).send({ error: ex })
|
return res.status(500).send({ error: ex })
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue