54 lines
1.2 KiB
TypeScript
54 lines
1.2 KiB
TypeScript
import { adminCredentials } from '~/components/credentials';
|
|
import { get } from './get';
|
|
import { getUrl } from './get-url';
|
|
import { headersWithAuth } from './headers-with-auth';
|
|
|
|
export const put = async (
|
|
id: string,
|
|
content: any,
|
|
isNew: boolean = false,
|
|
db = 'dyomedea_users',
|
|
overwrite_ = false,
|
|
credentials = adminCredentials()
|
|
) => {
|
|
console.log({ caller: 'put', id, isNew, db, content, credentials });
|
|
|
|
if (!credentials) {
|
|
return null;
|
|
}
|
|
const { database } = credentials;
|
|
|
|
if (!isNew) {
|
|
const previous = await get(id, db, credentials);
|
|
// console.log({
|
|
// caller: 'put / after get',
|
|
// id,
|
|
// isNew,
|
|
// db,
|
|
// content,
|
|
// previous,
|
|
// });
|
|
if (!!previous) {
|
|
content._rev = previous._rev;
|
|
if (!overwrite_) {
|
|
content.$ = previous.$;
|
|
}
|
|
}
|
|
}
|
|
|
|
const headers = headersWithAuth(credentials);
|
|
if (!headers) {
|
|
return null;
|
|
}
|
|
headers.set('Content-type', 'application/json; charset=UTF-8');
|
|
|
|
const response = await fetch(getUrl(id, db, credentials), {
|
|
method: 'PUT',
|
|
mode: 'cors',
|
|
headers,
|
|
body: JSON.stringify(content),
|
|
});
|
|
// console.log({ caller: 'put', id, isNew, db, status: response.status });
|
|
return await response.json();
|
|
};
|