78ef64a / social-store.mjs
2386 bytes
import { mkdirSync, readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { createPost, verifyPost } from './social.mjs'
import { createFsStore, parseJson, recordPath, requireThat, syncDirectory } from './storage.mjs'
export async function publishPost(root, identity, text, replyTo) {
const record = await createPost(identity, text, replyTo)
await storePost(root, record)
return record.id
}
export async function storePost(root, { id, signature, content }) {
const directory = join(root, 'posts')
mkdirSync(directory, { mode: 0o700, recursive: true })
syncDirectory(root)
const store = createFsStore(root)
if (await store.putPost(id, Buffer.from(JSON.stringify({ id, signature, content })))) return true
const existing = parseJson(await store.getPost(id))
requireThat(existing.id === id && existing.signature === signature && existing.content === content,
'Stored post does not match its record ID')
return false
}
export async function submitPost(root, identity, id, url) {
const bytes = await createFsStore(root).getPost(id)
requireThat(bytes, 'Local post not found')
const post = await verifyPost(parseJson(bytes))
requireThat(post.id === id && post.author === identity.author, 'Post must be signed by this identity')
const endpoint = new URL('/posts', url.origin)
const response = await fetch(endpoint, {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: bytes,
redirect: 'error', signal: AbortSignal.timeout(15000)
})
requireThat(response.ok, `Post submission failed (HTTP ${response.status})`)
requireThat((await response.json()).id === id, 'Server returned the wrong post ID')
}
export async function readFeed(root) {
const directory = join(root, 'posts')
let entries
try {
entries = readdirSync(directory, { withFileTypes: true })
} catch (error) {
if (error.code === 'ENOENT') return []
throw error
}
const posts = []
for (const entry of entries) {
if (!entry.isFile() || !/^[A-Za-z0-9_-]{43}$/.test(entry.name)) continue
const record = parseJson(readFileSync(join(directory, entry.name)))
const post = await verifyPost(record)
requireThat(recordPath(post.id) === entry.name, 'Post file does not match its record ID')
posts.push(post)
}
return posts.sort((a, b) => b.timestamp - a.timestamp || (a.id < b.id ? -1 : 1))
}
Git ยท Social feed