Back to marketplace
Utilities
neon-pg
A public TypeScript function.
Source Preview
typescript
import fn, { secret } from "@hostfunc/sdk";
import { neon } from "@neondatabase/serverless";
// A tiny notes API backed by your own Neon Postgres. The Neon serverless
// driver queries over HTTPS, so it runs anywhere fetch does — no TCP needed.
// Secret: NEON_DATABASE_URL — copy the connection string from your Neon
// dashboard (Connection Details → Connection string).
// POST { "action": "create", "text": "hello" } → insert a note
// POST { "action": "list" } (or GET) → latest 50 notes
// POST { "action": "update", "id": 1, "text": "…" }
// POST { "action": "delete", "id": 1 }
export async function main(input: { action?: string; id?: number; text?: string }) {
const sql = neon(await secret.getRequired("NEON_DATABASE_URL"));
await sql`CREATE TABLE IF NOT EXISTS notes (
id serial PRIMARY KEY,
text text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
)`;
switch (input.action) {
case "create": {
const text = input.text?.trim();
if (!text) return { ok: false, error: "Provide 'text'." };
const [note] = await sql`INSERT INTO notes (text) VALUES (${text}) RETURNING *`;
fn.log("info", "notes.created", { id: note?.id });
return { ok: true, note };
}
case "update": {
const text = input.text?.trim();
if (!input.id || !text) return { ok: false, error: "Provide 'id' and 'text'." };
const [note] = await sql`UPDATE notes SET text = ${text} WHERE id = ${input.id} RETURNING *`;
return note ? { ok: true, note } : { ok: false, error: "No such note." };
}
case "delete": {
if (!input.id) return { ok: false, error: "Provide 'id'." };
const deleted = await sql`DELETE FROM notes WHERE id = ${input.id} RETURNING id`;
return { ok: deleted.length > 0 };
}
default: {
const notes = await sql`SELECT * FROM notes ORDER BY created_at DESC LIMIT 50`;
fn.log("info", "notes.listed", { count: notes.length });
return { ok: true, notes };
}
}
}
About
No README has been published for this function yet.
Discussion
0Join the discussion
Sign in to comment, reply, and star functions you love.
Start the conversation.
Share a use case, ask a question, or suggest an improvement. Be the first to comment on this function.