Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/linkedin

Identity, generic requests, and guarded posting through the saved LinkedIn OAuth integration.

FollowFork

Files

video-upload-store.ts

50 lines · 1.5 KB · TypeScript
import type { VideoJob, VideoStore } from './video-upload-engine.ts'
type Sql = { sql(q: string, p?: unknown[]): Promise<unknown> }
const rows = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.rows) ? r.rows : [])
export function videoStore(storage: Sql): VideoStore {
	if (typeof storage?.sql !== 'function')
		throw new Error('Durable package storage is required before upload')
	let ready: Promise<unknown> | undefined
	const init = () =>
		(ready ??= storage.sql(
			'CREATE TABLE IF NOT EXISTS linkedin_upload_jobs_v1 (job_key TEXT PRIMARY KEY, version INTEGER NOT NULL, record TEXT NOT NULL)',
		))
	const parse = (r: any): VideoJob | null =>
		r ? { ...JSON.parse(r.record), version: Number(r.version) } : null
	return {
		async get(key) {
			await init()
			return parse(
				rows(
					await storage.sql(
						'SELECT record,version FROM linkedin_upload_jobs_v1 WHERE job_key = ?',
						[key],
					),
				)[0],
			)
		},
		async insert(j) {
			await init()
			return (
				rows(
					await storage.sql(
						'INSERT INTO linkedin_upload_jobs_v1 (job_key,version,record) VALUES (?,?,?) ON CONFLICT DO NOTHING RETURNING job_key',
						[j.key, j.version, JSON.stringify(j)],
					),
				).length === 1
			)
		},
		async save(j, version) {
			await init()
			const n = { ...j, version: version + 1 }
			return rows(
				await storage.sql(
					'UPDATE linkedin_upload_jobs_v1 SET version = ?,record = ? WHERE job_key = ? AND version = ? RETURNING version',
					[n.version, JSON.stringify(n), j.key, version],
				),
			).length === 1
				? n
				: null
		},
	}
}