node-mongo-demo
node.js and mongodb demo
git clone https://9o.is/git/node-mongo-demo.git
lucky7-bets.js
(1890B)
1 import Joi from 'joi';
2 import * as betEvents from '../events/lucky7-bets.js';
3 import Lucky7Session from '../models/lucky7-session.js';
4 import Lucky7Bet from '../models/lucky7-bet.js';
5 import EventStream from '../utils/event-stream.js';
6
7 const schema = Joi.object({
8 lucky: Joi.boolean().required(),
9 });
10
11 const errors = {
12 'SESSION_EXPIRED': { code: 'SESSION_EXPIRED', error: 'Session has expired' },
13 'SESSION_TIMER': { code: 'SESSION_TIMER', error: '5 seconds or less remaining' },
14 'SESSION_EXPIRING': { code: 'SESSION_EXPIRING', error: 'Session has no more games' },
15 };
16
17 export let changeStream;
18 export const subscribeEvents = () => {
19 changeStream = Lucky7Bet.watch().on('change', betEvents.onChange);
20 };
21
22 export const getEvents = async (req, res) => {
23 const { userId } = req;
24 const stream = new EventStream(req, res);
25 betEvents.subscribe(userId, stream);
26 };
27
28 export const create = async (req, res) => {
29 const { userId } = req;
30 const { value, error } = schema.validate(req.body);
31
32 if (error) {
33 return res.status(400).json({ error })
34 }
35
36 try {
37 const session = await Lucky7Session.findByUserId(userId);
38 const rollAt = session?.nextIntervalAt();
39
40 if (!session) return res.status(409).json(errors['SESSION_EXPIRED']);
41 if (!session.nextIntervalAt()) return res.status(409).json(errors['SESSION_EXPIRING']);
42 if (!session.isPlayable()) return res.status(409).json(errors['SESSION_TIMER']);
43
44 const bet = await Lucky7Bet.findOne({ userId, rollAt }) || new Lucky7Bet({ userId, rollAt });
45 bet.lucky = value.lucky;
46
47 if (!bet.played()) {
48 bet.play();
49 }
50
51 await bet.save();
52 res.status(201).json(bet.toRedactedObject());
53 } catch (error) {
54 console.error(error);
55 res.status(500).json({ message: 'Something went wrong' });
56 }
57 };