feat: upsert is easier
This commit is contained in:
6
main.ts
6
main.ts
@@ -1,5 +1,5 @@
|
||||
import { Jetstream } from "@skyware/jetstream";
|
||||
import { createNote, updateNote } from "./src/data/db"
|
||||
import { upsertNote } from "./src/data/db"
|
||||
|
||||
const jetstream = new Jetstream({
|
||||
wantedCollections: ["space.litenote.note"],
|
||||
@@ -9,7 +9,7 @@ jetstream.onCreate("space.litenote.note", (event) => {
|
||||
console.log("create", event);
|
||||
const {did, commit: {rkey, record}} = event
|
||||
|
||||
createNote({
|
||||
upsertNote({
|
||||
did,
|
||||
rkey,
|
||||
...record
|
||||
@@ -20,7 +20,7 @@ jetstream.onUpdate("space.litenote.note", (event) => {
|
||||
console.log("update", event);
|
||||
const {did, commit: {rkey, record}} = event
|
||||
|
||||
updateNote({
|
||||
upsertNote({
|
||||
did,
|
||||
rkey,
|
||||
...record
|
||||
|
||||
@@ -3,12 +3,23 @@ import type { Note } from "./note"
|
||||
|
||||
export const db = new DB("notes.db");
|
||||
|
||||
export const createNote = async (note: Note) => {
|
||||
return db.query(
|
||||
export const upsertNote = async (note: Note) => {
|
||||
db.query(
|
||||
`
|
||||
INSERT INTO note (
|
||||
title, content, publishedAt, createdAt, did, rkey
|
||||
) VALUES (?, ?, ?, ?, ?, ?)
|
||||
title,
|
||||
content,
|
||||
publishedAt,
|
||||
createdAt,
|
||||
did,
|
||||
rkey
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(did, rkey)
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
content = excluded.content,
|
||||
publishedAt = excluded.publishedAt
|
||||
`,
|
||||
[
|
||||
note.title,
|
||||
@@ -20,24 +31,3 @@ export const createNote = async (note: Note) => {
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
export const updateNote = async (note: Note) => {
|
||||
db.query(
|
||||
`
|
||||
UPDATE note
|
||||
SET
|
||||
title = ?,
|
||||
content = ?,
|
||||
publishedAt = ?
|
||||
WHERE did = ?
|
||||
AND rkey = ?
|
||||
`,
|
||||
[
|
||||
note.title,
|
||||
note.content,
|
||||
note.publishedAt, // publishedAt
|
||||
note.did,
|
||||
note.rkey,
|
||||
],
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user