stacker.news/api/resolvers/rewards.js

53 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-12-08 00:04:02 +00:00
import { AuthenticationError } from 'apollo-server-micro'
2023-02-08 19:38:04 +00:00
import { amountSchema, ssValidate } from '../../lib/validate'
2022-12-08 00:04:02 +00:00
import serialize from './serial'
export default {
Query: {
expectedRewards: async (parent, args, { models }) => {
// get the last reward time, then get all contributions to rewards since then
const lastReward = await models.earn.findFirst({
orderBy: {
createdAt: 'desc'
}
})
const [result] = await models.$queryRaw`
2022-12-19 22:27:52 +00:00
SELECT coalesce(FLOOR(sum(sats)), 0) as total, json_build_array(
json_build_object('name', 'donations', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'DONATION')), 0)),
json_build_object('name', 'fees', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type NOT IN ('BOOST', 'STREAM', 'DONATION'))), 0)),
json_build_object('name', 'boost', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'BOOST')), 0)),
json_build_object('name', 'jobs', 'value', coalesce(FLOOR(sum(sats) FILTER(WHERE type = 'STREAM')), 0))
2022-12-08 00:04:02 +00:00
) AS sources
FROM (
2022-12-19 22:27:52 +00:00
(SELECT ("ItemAct".msats - COALESCE("ReferralAct".msats, 0)) / 1000.0 as sats, act::text as type
2022-12-08 00:04:02 +00:00
FROM "ItemAct"
2022-12-19 22:27:52 +00:00
LEFT JOIN "ReferralAct" ON "ItemAct".id = "ReferralAct"."itemActId"
WHERE "ItemAct".created_at > ${lastReward.createdAt} AND "ItemAct".act <> 'TIP')
2022-12-08 00:04:02 +00:00
UNION ALL
2022-12-19 22:27:52 +00:00
(SELECT sats::FLOAT, 'DONATION' as type
2022-12-08 00:04:02 +00:00
FROM "Donation"
WHERE created_at > ${lastReward.createdAt})
) subquery`
return result
}
},
Mutation: {
donateToRewards: async (parent, { sats }, { me, models }) => {
if (!me) {
throw new AuthenticationError('you must be logged in')
}
2023-02-08 19:38:04 +00:00
await ssValidate(amountSchema, { amount: sats })
2022-12-08 00:04:02 +00:00
await serialize(models,
models.$queryRaw(
'SELECT donate($1, $2)',
sats, Number(me.id)))
return sats
}
}
}