spee.ch/server/models/trending.js

99 lines
2.5 KiB
JavaScript
Raw Normal View History

2018-12-14 18:42:37 +01:00
const chainquery = require('chainquery').default;
2018-10-24 10:43:30 +02:00
module.exports = (sequelize, { BOOLEAN, DATE, FLOAT, INTEGER, STRING }) => {
const Trending = sequelize.define(
'Trending',
{
time: { /* TODO: Historical analysis and log roll */
2018-11-11 01:11:12 +01:00
type : DATE(6),
2018-10-24 10:43:30 +02:00
defaultValue: sequelize.NOW,
},
isChannel: {
2018-11-11 01:11:12 +01:00
type : BOOLEAN,
2018-10-24 10:43:30 +02:00
defaultValue: false,
},
claimId: {
2018-11-11 01:11:12 +01:00
type : STRING,
2018-10-24 10:43:30 +02:00
defaultValue: null,
},
publisherId: {
2018-11-11 01:11:12 +01:00
type : STRING,
2018-10-24 10:43:30 +02:00
defaultValue: null,
},
intervalViews: {
2018-11-11 01:11:12 +01:00
type : INTEGER,
2018-10-24 10:43:30 +02:00
defaultValue: 0,
},
weight: {
2018-11-11 01:11:12 +01:00
type : FLOAT,
2018-10-24 10:43:30 +02:00
defaultValue: 0,
},
zScore: {
2018-11-11 01:11:12 +01:00
type : FLOAT,
2018-10-24 10:43:30 +02:00
defaultValue: 0,
},
pValue: {
2018-11-11 01:11:12 +01:00
type : FLOAT,
2018-10-24 10:43:30 +02:00
defaultValue: 0,
},
// TODO: Calculate t-statistics
},
{
freezeTableName: true,
2018-11-11 01:11:12 +01:00
timestamps : false, // don't use default timestamps columns
indexes : [
2018-10-24 10:43:30 +02:00
{
fields: ['claimId'],
},
{
fields: ['time', 'isChannel', 'claimId', 'publisherId', 'weight'],
},
],
}
);
Trending.getTrendingWeightData = async ({
hours = 2,
minutes = 0,
2018-11-11 01:11:12 +01:00
limit = 20,
2018-10-24 10:43:30 +02:00
} = {}) => {
let time = new Date();
time.setHours(time.getHours() - hours);
time.setMinutes(time.getMinutes() - minutes);
const sqlTime = time.toISOString().slice(0, 19).replace('T', ' ');
const selectString = 'DISTINCT(claimId), weight';
const whereString = `isChannel = false and time > '${sqlTime}'`;
2018-11-11 01:11:12 +01:00
const query = `SELECT ${selectString} FROM Trending WHERE ${whereString} ORDER BY weight DESC LIMIT ${limit}`;
2018-10-24 10:43:30 +02:00
2018-11-11 01:32:43 +01:00
return sequelize.query(query, { type: sequelize.QueryTypes.SELECT });
2018-10-24 10:43:30 +02:00
};
Trending.getTrendingClaims = async () => {
const trendingWeightData = await Trending.getTrendingWeightData();
const trendingClaimIds = [];
const trendingClaims = trendingWeightData.reduce((claims, trendingData) => {
trendingClaimIds.push(trendingData.claimId);
claims[trendingData.claimId] = {
2018-11-11 01:11:12 +01:00
...trendingData,
2018-10-24 10:43:30 +02:00
};
return claims;
}, {});
const claimData = await chainquery.claim.findAll({
where: {
claim_id: { [sequelize.Op.in]: trendingClaimIds },
},
});
return claimData.map((claimData) => {
return Object.assign(trendingClaims[claimData.claim_id], claimData.dataValues);
});
};
return Trending;
};