seed-ads.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import {
  2. PrismaClient,
  3. AdType,
  4. ImageSource,
  5. Prisma,
  6. } from '@prisma/mongo/client';
  7. const prisma = new PrismaClient();
  8. type SeedArgs = {
  9. clean: boolean;
  10. perType: number;
  11. };
  12. function parseArgs(argv: string[]): SeedArgs {
  13. const clean =
  14. argv.includes('--clean') ||
  15. argv.includes('-c') ||
  16. process.env.SEED_CLEAN === '1' ||
  17. process.env.SEED_CLEAN === 'true';
  18. const perTypeFromArg = (() => {
  19. const idx = argv.findIndex((a) => a === '--perType');
  20. if (idx >= 0) {
  21. const v = Number(argv[idx + 1]);
  22. if (Number.isFinite(v) && v > 0) return Math.floor(v);
  23. }
  24. const envValue = Number(process.env.SEED_PER_TYPE);
  25. if (Number.isFinite(envValue) && envValue > 0) return Math.floor(envValue);
  26. return 100;
  27. })();
  28. return { clean, perType: perTypeFromArg };
  29. }
  30. function nowEpochSec(): bigint {
  31. return BigInt(Math.floor(Date.now() / 1000));
  32. }
  33. function randInt(min: number, max: number): number {
  34. // inclusive range
  35. return Math.floor(Math.random() * (max - min + 1)) + min;
  36. }
  37. function pick<T>(arr: readonly T[]): T {
  38. return arr[randInt(0, arr.length - 1)];
  39. }
  40. function clampLen(s: string, maxLen: number): string {
  41. return s.length <= maxLen ? s : s.slice(0, maxLen);
  42. }
  43. function makeShortLabel(prefix: string, maxLen = 20): string {
  44. const tail = randInt(1, 9999).toString().padStart(4, '0');
  45. return clampLen(`${prefix}${tail}`, maxLen);
  46. }
  47. function makeCoverKey(adType: AdType, idx: number): string {
  48. const n = String(idx + 1).padStart(3, '0');
  49. return `ads/${adType.toLowerCase()}/img_${n}.png`;
  50. }
  51. function makeAdsUrl(adType: AdType): string {
  52. const id = randInt(100000, 999999);
  53. return `https://example.com/ads/${adType.toLowerCase()}?c=${id}`;
  54. }
  55. function makeContent(adType: AdType): string {
  56. const phrases = [
  57. '限时优惠',
  58. '新人专享',
  59. '立即领取',
  60. '官方推荐',
  61. '热卖爆款',
  62. '今日必看',
  63. '立刻参与',
  64. '福利放送',
  65. '超值精选',
  66. '品质保证',
  67. ] as const;
  68. const base = `${pick(phrases)} · ${adType}`;
  69. const extra = `|${pick(phrases)}|编号${randInt(1000, 9999)}`;
  70. return clampLen(base + extra, 500);
  71. }
  72. function makeTimeWindow(): { startDt: bigint; expiryDt: bigint } {
  73. const now = Number(nowEpochSec());
  74. const startOffsetDays = randInt(-30, 30);
  75. const start = now + startOffsetDays * 86400;
  76. const durationDays = randInt(7, 90);
  77. const expiry = start + durationDays * 86400;
  78. return { startDt: BigInt(start), expiryDt: BigInt(expiry) };
  79. }
  80. async function main() {
  81. const args = parseArgs(process.argv.slice(2));
  82. const tsNow = nowEpochSec();
  83. const adTypes = Object.values(AdType) as AdType[];
  84. if (args.clean) {
  85. await prisma.ads.deleteMany();
  86. console.log('[seed:ads] cleaned ads collection');
  87. }
  88. const advertiserPrefixes = [
  89. '广告商A',
  90. '广告商B',
  91. '广告商C',
  92. '品牌X',
  93. '品牌Y',
  94. '品牌Z',
  95. ] as const;
  96. const titlePrefixes = [
  97. '爆款推荐',
  98. '限时福利',
  99. '新品上线',
  100. '今日热推',
  101. '官方活动',
  102. '专属礼包',
  103. ] as const;
  104. const batch: Prisma.AdsCreateManyInput[] = [];
  105. for (const adType of adTypes) {
  106. for (let idx = 0; idx < args.perType; idx++) {
  107. const { startDt, expiryDt } = makeTimeWindow();
  108. const advertiser = makeShortLabel(pick(advertiserPrefixes), 20);
  109. const title = makeShortLabel(pick(titlePrefixes), 20);
  110. const adsCoverImg =
  111. Math.random() < 0.85 ? makeCoverKey(adType, idx) : null;
  112. const adsUrl = Math.random() < 0.9 ? makeAdsUrl(adType) : null;
  113. const adsContent = Math.random() < 0.8 ? makeContent(adType) : null;
  114. batch.push({
  115. adType,
  116. advertiser,
  117. title,
  118. adsContent,
  119. adsCoverImg,
  120. adsUrl,
  121. imgSource: ImageSource.LOCAL_ONLY,
  122. startDt,
  123. expiryDt,
  124. seq: randInt(0, 9999),
  125. status: Math.random() < 0.9 ? 1 : 0,
  126. createAt: tsNow,
  127. updateAt: tsNow,
  128. });
  129. }
  130. }
  131. const result = await prisma.ads.createMany({ data: batch });
  132. console.log(
  133. `[seed:ads] adTypes=${adTypes.length} perType=${args.perType} inserted=${result.count} clean=${args.clean}`,
  134. );
  135. }
  136. main()
  137. .catch((error) => {
  138. console.error('[seed:ads] failed:', error);
  139. process.exitCode = 1;
  140. })
  141. .finally(async () => {
  142. await prisma.$disconnect();
  143. });