Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@christianalfoni
Last active March 27, 2019 15:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianalfoni/026d03cd3f992cf1822fff0ec646f34a to your computer and use it in GitHub Desktop.
Save christianalfoni/026d03cd3f992cf1822fff0ec646f34a to your computer and use it in GitHub Desktop.
firebase
export const open: Action = async ({ state, actions, effects }) => {
state.currentPage = Page.ADMIN
const messageUpdates = await effects.api.getAdminMessageUpdates()
state.admin.messageUpdates = messageUpdates
state.admin.users = await effects.api.getUsers(
messageUpdates.map((update) => update.userUid)
)
if (state.admin.messageUpdates.length) {
state.admin.isLoadingFeed = true
const firstUpdate = state.admin.messageUpdates[0]
const userUid = firstUpdate.userUid
state.admin.currentUserUid = userUid
state.admin.feeds[userUid] = await effects.api.getFeed(userUid)
state.admin.isLoadingFeed = false
effects.api.listenToFeedUpdates(userUid, actions.admin.onFeedUpdate)
}
effects.api.listenToAdminMessageUpdates(actions.admin.onAdminMessageUpdate)
}
export const api = (() => {
function configureFirebase(config) {
firebase.initializeApp(config)
firebase.auth().useDeviceLanguage()
return firebase.database()
}
const db = configureFirebase({...})
return {
listenToFeedUpdates(
uid: string,
action: (update: FeedUpdate<any>) => void
) {
if (feedUpdateUidsRegistered.includes(uid)) {
return
}
feedUpdateUidsRegistered.push(uid)
const ref = db.ref('feeds/' + uid)
ref
.orderByChild('created')
.startAt(Date.now())
.on('child_added', (snapshot) =>
action({
...snapshot.val(),
uid: snapshot.key,
})
)
ref.on('child_changed', (snapshot) =>
action({
...snapshot.val(),
uid: snapshot.key,
})
)
},
listenToAdminMessageUpdates(action: (update: AdminMessageUpdate) => void) {
db.ref('messageUpdates').off()
const adminMessageUpdateCallback = (snapshot) => {
const key = snapshot.key
const value: AdminMessageUpdate = snapshot.val()
if (
!adminMessageUpdatesByUpdated[key] ||
adminMessageUpdatesByUpdated[key] !== value.updated
) {
adminMessageUpdatesByUpdated[key] = value.updated
action(value)
}
}
db.ref('messageUpdates').on('child_added', adminMessageUpdateCallback)
db.ref('messageUpdates').on('child_changed', adminMessageUpdateCallback)
},
unlistenToFeedUpdates(uid: string) {
db.ref('feeds/' + uid).off('child_added')
},
setFeedOpened(uid: string) {
db.ref('messageUpdates/' + uid).update({
opened: firebase.database.ServerValue.TIMESTAMP,
updated: firebase.database.ServerValue.TIMESTAMP,
})
},
setFeedResponded(
uid: string,
responded: number = firebase.database.ServerValue.TIMESTAMP as number
) {
db.ref('messageUpdates/' + uid).update({
responded,
})
},
submitMessage(ownerUid: string, data: MessageUpdate) {
return new Promise((resolve) => {
const update: FeedUpdate<MessageUpdate> = {
type: FeedUpdateType.MESSAGE,
created: firebase.database.ServerValue.TIMESTAMP as number,
data,
userUid: ownerUid,
}
db.ref('feeds/' + ownerUid)
.push(update)
.then(resolve)
})
},
updateMessage(userUid: string, messageUid: string, data: MessageUpdate) {
return new Promise((resolve) => {
db.ref('feeds/' + userUid + '/' + messageUid + '/data')
.set(data)
.then(resolve)
})
},
getAdminMessageUpdates(): Promise<AdminMessageUpdate[]> {
return new Promise((resolve) => {
db.ref('/messageUpdates')
.orderByChild('updated')
.once('value')
.then((snapshot) => {
resolve(values(snapshot.val()))
})
})
},
getUser(uid: string) {
return db
.ref('/users/' + uid)
.once('value')
.then((snapshot) => snapshot.val())
},
getUsers(uids: string[]): Promise<{ [uid: string]: User }> {
return Promise.all(
uids.map((uid) => db.ref('/users/' + uid).once('value'))
).then((snapshots) =>
snapshots.reduce(
(aggr, snapshot) =>
Object.assign(aggr, {
[snapshot.key]: snapshot.val(),
}),
{}
)
)
},
getFeed(uid: string): Promise<FeedUpdate<any>[]> {
return new Promise((resolve, reject) => {
db.ref('/feeds/' + uid)
.orderByChild('created')
.limitToLast(500)
.once('value')
.then((snapshot) => {
const updates = []
snapshot.forEach((update) => {
updates.push({
...update.val(),
uid: update.key,
})
})
resolve(sortBy(updates, ['created']))
})
.catch(reject)
})
},
isUserAdmin(uid: string): Promise<boolean> {
return new Promise((resolve, reject) => {
db.ref('/admins/' + uid)
.once('value')
.then((snapshot) => {
const value = snapshot.val()
resolve(Boolean(value))
})
.catch(reject)
})
},
onAuthenticated(action: (uid: string) => void) {
firebase.auth().onAuthStateChanged((user) => {
if (user) action(user.uid)
else action(null)
})
},
signIn(customToken: string): Promise<string> {
console.log(customToken)
return new Promise((resolve, reject) => {
firebase
.auth()
.signInWithCustomToken(customToken)
.then((result) => {
resolve(result.user.uid)
})
.catch(reject)
})
},
signOut() {
firebase
.auth()
.signOut()
.then(() => location.reload(true))
},
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment