Update tag associations without recreating document text assets
waterfall-wiki CI and deployment / verify-and-deploy (push) Has been cancelled
waterfall-wiki CI and deployment / verify-and-deploy (push) Has been cancelled
This commit is contained in:
@@ -57,3 +57,24 @@ export async function saveNote(id:string,input:z.infer<typeof noteEditInput>,rea
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export const noteTagsInput=z.object({tags:z.array(z.uuid()).max(50),revision:z.string().regex(/^[0-9a-f]{64}$/)}).strict();
|
||||
/** A tag edit never replaces a text asset, cover or media association. */
|
||||
export async function saveNoteTags(id:string,input:z.infer<typeof noteTagsInput>,read:(client:PoolClient)=>Promise<ExploreEntry|null>){
|
||||
await transaction(async client=>{
|
||||
await client.query('SELECT pg_advisory_xact_lock(hashtextextended($1,0))',['note-edit:'+id]);
|
||||
const stored=(await client.query(`SELECT id FROM posts WHERE ${/^[0-9a-f]{24}$/.test(id)?'public_id':'id'}=$1 FOR UPDATE`,[id])).rows[0];
|
||||
const current=await read(client);if(!current)throw Error('Note not found');
|
||||
if(current.revision!==input.revision)throw new NoteEditConflict('这篇笔记已被修改,请重新打开编辑后再保存。');
|
||||
const ids=[...new Set(input.tags)];if((await client.query('SELECT id FROM tags WHERE id=ANY($1::uuid[])',[ids])).rowCount!==ids.length)throw Error('Tag not found');
|
||||
if(stored){
|
||||
await client.query('UPDATE posts SET updated_at=now(),edited_at=now() WHERE id=$1',[stored.id]);
|
||||
await client.query('DELETE FROM post_tags WHERE post_id=$1',[stored.id]);
|
||||
for(const tagId of ids)await client.query('INSERT INTO post_tags(post_id,tag_id) VALUES($1,$2)',[stored.id,tagId]);
|
||||
}else{
|
||||
await client.query(`INSERT INTO note_edits(page_id,title,description,markdown) VALUES($1,$2,$3,$4) ON CONFLICT(page_id) DO UPDATE SET updated_at=now()`,[id,current.title,current.description,current.editableMarkdown]);
|
||||
await client.query('DELETE FROM note_edit_tags WHERE page_id=$1',[id]);
|
||||
for(const tagId of ids)await client.query('INSERT INTO note_edit_tags(page_id,tag_id) VALUES($1,$2)',[id,tagId]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import {serveApiDocumentation} from '@/lib/api-documentation';
|
||||
import {z} from 'zod';
|
||||
import type {NextApiRequest,NextApiResponse} from 'next';
|
||||
import {getEntry} from '@/lib/explore';
|
||||
import {tags} from '@/lib/library';
|
||||
import {noteEditInput,saveNote,NoteEditConflict} from '@/lib/note-edits';
|
||||
import {noteEditInput,noteTagsInput,saveNote,saveNoteTags,NoteEditConflict} from '@/lib/note-edits';
|
||||
import {sameOrigin,apiError} from '@/lib/api';
|
||||
export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
if(serveApiDocumentation(req,res,'/api/notes/{id}'))return;
|
||||
@@ -12,7 +11,9 @@ export default async function handler(req:NextApiRequest,res:NextApiResponse){
|
||||
try{
|
||||
const id=String(req.query.id||'');const entry=await getEntry(id);if(!entry)return res.status(404).json({error:'笔记不存在'});
|
||||
if(req.method==='GET')return res.json({entry,tags:await tags()});
|
||||
sameOrigin(req);const body=req.method==='PATCH'?{title:entry.title,description:entry.description,markdown:entry.editableMarkdown,...z.object({tags:z.array(z.uuid()).max(50),revision:z.string().regex(/^[0-9a-f]{64}$/)}).strict().parse(req.body)}:req.body;const input=noteEditInput.parse(body);await saveNote(id,input,client=>getEntry(id,client));
|
||||
sameOrigin(req);
|
||||
if(req.method==='PATCH')await saveNoteTags(id,noteTagsInput.parse(req.body),client=>getEntry(id,client));
|
||||
else await saveNote(id,noteEditInput.parse(req.body),client=>getEntry(id,client));
|
||||
return res.json({entry:await getEntry(id)});
|
||||
}catch(e){if(e instanceof NoteEditConflict)return res.status(409).json({error:e.message});return apiError(res,e);}
|
||||
}
|
||||
|
||||
@@ -167,8 +167,10 @@ test('real PostgreSQL + S3 notes, flat tags, resource sharing and video processi
|
||||
const plain=await request('/api/tags',{name:'#可随时添加'});assert.equal(plain.kind,'normal');
|
||||
const beforeTags=(await request('/api/notes/'+targetNote.id)).entry;
|
||||
const patchTags=(payload:unknown)=>fetch(base+'/api/notes/'+targetNote.id,{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)});
|
||||
const textLinksBefore=(await db().query("SELECT a.id FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND a.kind='text' ORDER BY a.id",[targetNote.id])).rows;
|
||||
const assigned=await patchTags({tags:[plain.id,entryLabel.id],revision:beforeTags.revision});assert.equal(assigned.status,200,await assigned.clone().text());
|
||||
const afterTags=(await request('/api/notes/'+targetNote.id)).entry;assert.deepEqual(afterTags.categories,[plain.name]);assert.equal(afterTags.systemTags[0].system_key,'document-entry');assert.equal(afterTags.editableMarkdown,beforeTags.editableMarkdown);
|
||||
assert.deepEqual((await db().query("SELECT a.id FROM post_assets pa JOIN assets a ON a.id=pa.asset_id WHERE pa.post_id=$1 AND a.kind='text' ORDER BY a.id",[targetNote.id])).rows,textLinksBefore,'Tag-only PATCH preserves the existing text assets');
|
||||
const systemFeed=await request('/api/explore-feed?category='+encodeURIComponent(entryLabel.name));assert.ok(systemFeed.entries.some((e:{id:string})=>e.id===targetNote.id));
|
||||
assert.equal((await patchTags({tags:[],revision:beforeTags.revision})).status,409);
|
||||
assert.equal((await patchTags({tags:[],revision:afterTags.revision})).status,200);
|
||||
|
||||
Reference in New Issue
Block a user