egirlskey/packages/backend/src/server/api/common/inject-promo.ts

35 lines
962 B
TypeScript
Raw Normal View History

2020-02-17 23:41:32 +00:00
import rndstr from 'rndstr';
import { Note } from '@/models/entities/note';
import { User } from '@/models/entities/user';
import { PromoReads, PromoNotes, Notes, Users } from '@/models/index';
2020-02-17 23:41:32 +00:00
2020-02-18 10:05:11 +00:00
export async function injectPromo(timeline: Note[], user?: User | null) {
2020-02-17 23:41:32 +00:00
if (timeline.length < 5) return;
// TODO: readやexpireフィルタはクエリ側でやる
2020-02-18 10:05:11 +00:00
const reads = user ? await PromoReads.find({
2021-12-09 14:58:30 +00:00
userId: user.id,
2020-02-18 10:05:11 +00:00
}) : [];
2020-02-17 23:41:32 +00:00
let promos = await PromoNotes.find();
promos = promos.filter(n => n.expiresAt.getTime() > Date.now());
promos = promos.filter(n => !reads.map(r => r.noteId).includes(n.noteId));
if (promos.length === 0) return;
2020-02-18 10:05:11 +00:00
// Pick random promo
2020-02-17 23:41:32 +00:00
const promo = promos[Math.floor(Math.random() * promos.length)];
2021-02-13 06:33:38 +00:00
const note = await Notes.findOneOrFail(promo.noteId);
2020-02-17 23:41:32 +00:00
// Join
2021-02-13 06:33:38 +00:00
note.user = await Users.findOneOrFail(note.userId);
2020-02-17 23:41:32 +00:00
2020-02-18 10:05:11 +00:00
(note as any)._prId_ = rndstr('a-z0-9', 8);
2020-02-17 23:41:32 +00:00
// Inject promo
timeline.splice(3, 0, note);
}