Skip to content

Instantly share code, notes, and snippets.

@daGrevis
Created August 29, 2018 22:44
Show Gist options
  • Select an option

  • Save daGrevis/9e80d1220add1bdc8d06f1c76d2a7888 to your computer and use it in GitHub Desktop.

Select an option

Save daGrevis/9e80d1220add1bdc8d06f1c76d2a7888 to your computer and use it in GitHub Desktop.
const postgres = require('../index')
const getMessagesQuery = (serverId, channelName, connectionId) =>
postgres('ircMessages')
.where({ serverId, to: channelName })
.where(function() {
this.where({ isPublic: true })
if (connectionId) {
this.orWhere({ connectionId })
}
})
const getMessageCreatedAtQuery = messageId =>
postgres
.select('createdAt')
.from('ircMessages')
.where({ id: messageId })
.limit(1)
const getMessages = async ({ serverId, channelName, connectionId, limit }) =>
getMessagesQuery(serverId, channelName, connectionId)
.orderBy('createdAt')
.limit(limit)
const getMessagesBefore = async ({ serverId, channelName, connectionId, before, limit }) =>
postgres
.select()
.from(
getMessagesQuery(serverId, channelName, connectionId)
.where('createdAt', '<=', getMessageCreatedAtQuery(before))
.where('id', '!=', before)
.orderBy('createdAt', 'desc')
.limit(limit)
.as('messages')
)
.orderBy('createdAt')
const getMessagesAfter = async ({ serverId, channelName, connectionId, after, limit }) =>
getMessagesQuery(serverId, channelName, connectionId)
.where('createdAt', '>=', getMessageCreatedAtQuery(after))
.where('id', '!=', after)
.orderBy('createdAt')
.limit(limit)
const getMessagesAround = async ({ serverId, channelName, connectionId, around, limit }) => {
const halfLimit = Math.ceil(limit / 2)
return postgres
.select()
.from(
postgres.union([
getMessagesQuery(serverId, channelName, connectionId)
.where('createdAt', '<=', getMessageCreatedAtQuery(around))
.orderBy('createdAt', 'desc')
.limit(halfLimit),
getMessagesQuery(serverId, channelName, connectionId)
.where('createdAt', '>', getMessageCreatedAtQuery(around))
.where('id', '!=', around)
.orderBy('createdAt')
.limit(limit - halfLimit),
], true).as('messages')
)
.orderBy('createdAt')
}
module.exports = {
getMessages,
getMessagesBefore,
getMessagesAfter,
getMessagesAround,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment