Skip to content

Instantly share code, notes, and snippets.

@urbanisierung
Created December 10, 2020 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save urbanisierung/09c04534118809304a6df1d665e21357 to your computer and use it in GitHub Desktop.
Save urbanisierung/09c04534118809304a6df1d665e21357 to your computer and use it in GitHub Desktop.
import { v4 } from 'uuid'
import { Document } from '../types/Document.type'
import { Mood, MoodRequest } from '../types/Mood.type'
import { User } from '../types/User.type'
import { Error, ErrorType } from '../utils/Error'
import { StorageController } from './storage.controller'
export class MoodController {
constructor(private store: StorageController) {}
public createRequest(user: User) {
const now = new Date().getTime()
const moodRequest: MoodRequest = {
uuid: v4(),
team: user.team,
ts: now,
expiration: now + 1000 * 60 * 60 * 12,
}
return moodRequest
}
public async saveMoodRequest(moodRequest: MoodRequest) {
await this.store.set(Document.MOOD_REQUEST, moodRequest.uuid, moodRequest)
}
public async setMood(moodRequestId: string, moodValue: number) {
const moodRequest: MoodRequest = await this.store.get(
Document.MOOD_REQUEST,
moodRequestId,
)
if (!moodRequest) {
throw new Error(ErrorType.NotFound, `Mood not found`)
}
const now = new Date().getTime()
if (moodRequest.expiration < now) {
this.store.delete(Document.MOOD_REQUEST, moodRequestId)
throw new Error(ErrorType.BadRequest, `Request expired`)
}
const mood: Mood = {
uuid: moodRequest.uuid,
mood: moodValue,
team: moodRequest.team,
ts: now,
requestTs: moodRequest.ts,
}
await Promise.all([
this.store.delete(Document.MOOD_REQUEST, moodRequestId),
this.store.set(Document.MOOD, mood.uuid, mood),
])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment