webmention-handler-netlify-blobs
Version:
Netlify Blobs storage to work with webmention-handler
101 lines (90 loc) • 2.79 kB
JavaScript
import { getStore, listStores } from '@netlify/blobs'
// https://docs.netlify.com//blobs/overview/
export default class BlobStorage {
constructor(options) {
this.
}
addPendingMention = async (mention) => {
const store = getStore({ name: 'queue', ...this.
const id = this.
await store.setJSON(id, mention)
return {
_id: id,
...mention,
processed: false
}
}
getNextPendingMentions = async () => {
const store = getStore({ name: 'queue', ...this.
const { blobs } = await store.list()
const mentions = []
for (const { key } of blobs) {
const value = await store.get(key, { type: 'json' })
mentions.push({
_id: key,
...value
})
await store.delete(key)
}
return mentions
}
deleteMention = async (mention) => {
const store = getStore({ name: 'target', ...this.
const key = mention.target
const target = await store.get(key, { type: 'json' })
if (!target) return
const mentions = target.filter(m => m.source !== mention.source)
if (!mentions) {
console.log(`[INFO] Delete ${mention.target} from 'target'`)
await store.delete(key)
} else {
console.log(`[INFO] Update ${mention.target} in 'target'`)
await store.setJSON(key, mentions)
}
}
getMentionsForPage = async (page, type) => {
const store = getStore({ name: 'target', ...this.
const mentions = await store.get(page, { type: 'json' })
if (!type) return mentions
return mentions.filter(m => type === m.type)
}
storeMentionForPage = async (page, mention) => {
await this.storeMentionsForPage(page, [mention])
return mention
}
storeMentionsForPage = async (page, mentions) => {
const store = getStore({ name: 'target', ...this.
let target = await store.get(page, { type: 'json' }) || []
for (const mention of mentions) {
target = target.filter(m => m.source !== mention.source)
}
await store.setJSON(page, [ ...target, ...mentions ])
return mentions
}
getAllMentions = async () => {
const store = getStore({ name: 'target', ...this.
const { blobs } = await store.list()
const mentions = {}
for (const { key } of blobs) {
const value = await store.get(key, { type: 'json' })
mentions[key] = value
}
return mentions
}
clearAll = async () => {
let total = 0
const { stores } = await listStores(this.
for (const name of stores) {
const store = getStore({ name, ...this.
const { blobs } = await store.list()
console.log(`[INFO] Removing ${blobs.length} from ${name}`)
for (const { key } of blobs) {
await store.delete(key)
total++
}
}
return total
}
}