traxxx-web/src/campaigns.js

48 lines
1.5 KiB
JavaScript
Raw Normal View History

import { knexOwner as knex } from './knex.js';
import { curateEntity } from './entities.js';
function curateCampaign(campaign) {
if (!campaign) {
return null;
}
return {
id: campaign.id,
url: campaign.url,
banner: campaign.banner && {
id: campaign.banner.id,
type: campaign.banner.type,
entity: campaign.banner_entity && curateEntity({ ...campaign.banner_entity, parent: campaign.banner_parent_entity }),
tags: campaign.banner_tags?.map((tag) => ({
id: tag.id,
slug: tag.slug,
name: tag.name,
})) || [],
},
affiliateId: campaign.affiliate_id,
};
}
export async function getRandomCampaign(options = {}) {
const campaign = await knex.raw(`
SELECT
campaigns.*, row_to_json(banners) as banner, row_to_json(entities) as banner_entity, row_to_json(parents) as banner_parent_entity, json_agg(tags) filter (where tags.id is not null) as banner_tags
FROM campaigns
LEFT JOIN banners ON banners.id = campaigns.banner_id
LEFT JOIN banners_tags ON banners_tags.banner_id = banners.id
LEFT JOIN tags ON tags.id = banners_tags.tag_id
LEFT JOIN entities ON entities.id = banners.entity_id
LEFT JOIN entities as parents ON parents.id = entities.parent_id
WHERE campaigns.banner_id IS NOT NULL
AND ratio >= :minRatio
AND ratio <= :maxRatio
GROUP BY campaigns.id, banners.id, entities.id, parents.id
ORDER BY RANDOM()
`, {
minRatio: options.minRatio || 0,
maxRatio: options.maxRatio || 1000,
});
return curateCampaign(campaign.rows[0]);
}