2019-01-21 22:32:42 +00:00
|
|
|
import { Q } from '@nozbe/watermelondb'
|
|
|
|
import database from '../db'
|
2019-01-22 19:16:58 +00:00
|
|
|
import { getAllPledges } from '../utils/pledges'
|
|
|
|
import { getProfilesById } from './profiles'
|
2019-01-21 22:32:42 +00:00
|
|
|
|
2019-01-22 19:16:58 +00:00
|
|
|
const createPledge = (pledge, data, profiles) => {
|
2019-01-21 22:32:42 +00:00
|
|
|
const { id, owner, amount, token, commitTime, nDelegates, pledgeState, intendedProject } = data
|
2019-01-22 19:16:58 +00:00
|
|
|
const profile = profiles.find(p => p.idProfile == owner)
|
2019-01-21 22:32:42 +00:00
|
|
|
pledge.pledgeId = id
|
|
|
|
pledge.owner = Number(owner)
|
2019-01-22 19:39:25 +00:00
|
|
|
pledge.amount = amount
|
2019-01-21 22:32:42 +00:00
|
|
|
pledge.token = token
|
|
|
|
pledge.commitTime = Number(commitTime)
|
|
|
|
pledge.nDelegates = Number(nDelegates)
|
|
|
|
pledge.pledgeState = pledgeState
|
|
|
|
pledge.intendedProject = Number(intendedProject)
|
2019-01-22 19:16:58 +00:00
|
|
|
pledge.profile.id = profile.id
|
2019-01-21 22:32:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const pledgesCollection = database.collections.get('pledges')
|
|
|
|
export const addPledge = async data => {
|
|
|
|
return await database.action(async () => {
|
|
|
|
const res = await pledgesCollection.create(pledge => createPledge(pledge, data))
|
|
|
|
return res
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-01-22 19:16:58 +00:00
|
|
|
export const batchAddPledges = async (pledges, profiles = []) => {
|
|
|
|
const batch = pledges.map(data => {
|
|
|
|
return pledgesCollection.prepareCreate(pledge => createPledge(pledge, data, profiles))
|
2019-01-21 22:32:42 +00:00
|
|
|
})
|
|
|
|
console.log({batch})
|
|
|
|
return await database.action(async () => await database.batch(...batch))
|
|
|
|
}
|
|
|
|
|
2019-01-22 19:16:58 +00:00
|
|
|
const getLastPledge = pledges => {
|
|
|
|
const pledgeId = pledges.length
|
|
|
|
? pledges.sort((a,b) => b.pledgeId - a.pledgeId)[0].pledgeId
|
|
|
|
: 1
|
|
|
|
return pledgeId
|
|
|
|
}
|
|
|
|
export const getAndAddPledges = async () => {
|
|
|
|
const pledges = await getLocalPledges()
|
|
|
|
const pledgeId = getLastPledge(pledges)
|
|
|
|
const newPledges = await getAllPledges(pledgeId + 1)
|
|
|
|
const pledgeIds = newPledges.map(p => p.owner)
|
|
|
|
const profiles = await getProfilesById(pledgeIds)
|
|
|
|
batchAddPledges(newPledges, profiles)
|
2019-01-21 22:32:42 +00:00
|
|
|
}
|
|
|
|
|
2019-01-22 19:16:58 +00:00
|
|
|
export const getLocalPledges = async () => {
|
2019-01-21 22:32:42 +00:00
|
|
|
const events = await pledgesCollection.query().fetch()
|
|
|
|
return events
|
|
|
|
}
|
|
|
|
|
|
|
|
export const getPledgeById = async id => {
|
|
|
|
const event = await pledgesCollection.query(
|
|
|
|
Q.where('id_profile', id)
|
|
|
|
).fetch()
|
|
|
|
return event
|
|
|
|
}
|