directus-extension-upsert
Version:
As the name suggests a basic extension for upserting records in a single API call, it will check if the record exists and if so, update it, otherwise it will create it.
2 lines (1 loc) • 735 B
JavaScript
;const e={success:!0,msg:"Success",code:200,data:null};var s={id:"upsert",handler:async(s,{services:c,database:t,getSchema:a})=>{const{ItemsService:o}=c;s.post("/:collection",(async(s,c,t)=>{try{const{collection:t}=s.params;if(!t)throw"Missing collection";let a=s.body||{};const{filter:n={},body:i={}}=a;if(!n||!Object.keys(n).length)return c.json({...e,success:!1,msg:"Missing filter"});const r=new o(t,{schema:s.schema,accountability:s.accountability}),l=r.schema.collections[t].primary,m={...n},u=await r.knex.select(l).from(t).where(m).first();u?(await r.updateOne(u[l],i),c.json({...e,msg:"Update Success"})):(await r.createOne(i),c.json({...e,msg:"Create Success",code:201}))}catch(e){throw e}}))}};module.exports=s;