diff --git a/src/lib/routes/admin-api/user-splash-controller.ts b/src/lib/routes/admin-api/user-splash-controller.ts new file mode 100644 index 0000000000..c2e9ad7b14 --- /dev/null +++ b/src/lib/routes/admin-api/user-splash-controller.ts @@ -0,0 +1,76 @@ +import { Response } from 'express'; + +import Controller from '../controller'; +import { Logger } from '../../logger'; +import { IUnleashConfig } from '../../types/option'; +import { IUnleashServices } from '../../types/services'; +import UserSplashService from '../../services/user-splash-service'; +import { IAuthRequest } from '../unleash-types'; + +interface ISplashBody { + seen: boolean; + splashId: string; +} + +class UserSplashController extends Controller { + private logger: Logger; + private userSplashService: UserSplashService; + + constructor( + config: IUnleashConfig, + { userSplashService }: Pick, + ) { + super(config); + this.logger = config.getLogger('splash-controller.ts'); + this.userSplashService = userSplashService; + + this.post('/', this.recordSplash); + this.put('/:id', this.updateSplashSettings); + } + + private async recordSplash( + req: IAuthRequest, + res: Response, + ): Promise { + const BAD_REQUEST = 400; + const { user } = req; + + const { splashId } = req.body; + + if (!splashId) { + res.status(BAD_REQUEST).json({ + error: 'splashId must be present.', + }); + return; + } + + const splash = { + ...req.body, + userId: user.id, + seen: req.body.seen || false, + }; + + const updated = await this.userSplashService.updateSplash(splash); + res.json(updated); + } + + private async updateSplashSettings( + req: IAuthRequest, + res: Response, + ): Promise { + const { user } = req; + const { id } = req.params; + + const splash = { + ...req.body, + splashId: id, + userId: user.id, + seen: req.body.seen || false, + }; + + const updated = await this.userSplashService.updateSplash(splash); + res.json(updated); + } +} + +module.exports = UserSplashController; diff --git a/src/migrations/20211109123505-add-cascade-for-user-splash.js b/src/migrations/20211109123505-add-cascade-for-user-splash.js new file mode 100644 index 0000000000..9a62b4e4e8 --- /dev/null +++ b/src/migrations/20211109123505-add-cascade-for-user-splash.js @@ -0,0 +1,16 @@ +exports.up = function (db, cb) { + db.runSql( + ` + ALTER TABLE user_splash DROP CONSTRAINT user_splash_user_id_fkey; + ALTER TABLE user_splash + ADD CONSTRAINT user_splash_user_id_fkey + FOREIGN KEY (user_id) + REFERENCES users(id) ON DELETE CASCADE; +`, + cb, + ); +}; + +exports.down = function (db, cb) { + db.runSql('', cb); +};