const router = require('express').Router() import { Member, Post, Proposal, Council, Consul, } from '../db/models' import donate from '../donate' const findMember = (handle: number | string) => handle > 0 ? Member.findByPk(handle) : Member.findOne({ where: { handle } }) const findMemberWithIncludes = (handle: number | string) => handle > 0 ? Member.findByIdWithIncludes(handle) : Member.findWithIncludes({ where: { handle } }) router.get('/', async (req: any, res: any, next: any) => { try { Member.findAll().then((m: any) => res.json(m)) } catch (err) { next(err) } }) router.get('/:id', async (req: any, res: any, next: any) => { try { res.json(await findMemberWithIncludes(req.params.id)) } catch (err) { next(err) } }) router.get('/:id/posts', async (req: any, res: any, next: any) => { try { const { id } = await findMember(req.params.id) if (!id) res.json({}) const posts = await Post.findWithIncludes({ where: { authorId: id } }) res.json(posts) } catch (err) { next(err) } }) router.get('/:id/proposals', async (req: any, res: any, next: any) => { try { const { id } = await findMember(req.params.id) if (!id) res.json({}) const proposals = await Proposal.findWithIncludes({ where: { authorId: id }, }) res.json(proposals) } catch (err) { next(err) } }) router.get('/:id/terms', async (req: any, res: any, next: any) => { try { const { id } = await findMember(req.params.id) if (!id) res.json({}) const terms = await Consul.findWithIncludes({ where: { memberId: id } }) res.json(terms) } catch (err) { next(err) } }) router.get('/:id/votes', async (req: any, res: any, next: any) => { try { const member = await findMember(req.params.id) if (!member) res.json({}) const memberId = member.id const proposals = await Consul.findAll({ where: { memberId }, include: [ { association: 'votes', include: [ { model: Proposal, attributes: ['title'], }, ], }, ], }) const councils = await Consul.findAll({ include: [ { model: Member, attributes: ['handle'] }, { association: 'voters', required: true, where: { memberId } }, ], }) return res.json({ councils, proposals }) } catch (err) { next(err) } }) router.post('/', async (req: any, res: any, next: any) => { res.status(402).send(donate) try { //Member.create(req.body).then((member: any) => res.json(member)) } catch (err) { next(err) } }) router.put('/:id', async (req: any, res: any, next: any) => { res.status(402).send(donate) try { // Member.findByPk(req.params.id).then((member: any) => // member.update(req.body).then((m: any) => res.json(m)) // ) } catch (err) { next(err) } }) router.post('/:id/delete', async (req: any, res: any, next: any) => { res.status(402).send(donate) try { //Member.findByPk(req.params.id).then((member:any)=>res.json(member.delete()) } catch (err) { next(err) } }) module.exports = router