Add client-side User class derived from @dougal/user.

Adds methods to communicate with the backend.
This commit is contained in:
D. Berge
2025-07-24 20:37:50 +02:00
parent 683f5680b1
commit 3b7e4c9f0b

View File

@@ -0,0 +1,97 @@
import { User as BaseUser } from '@dougal/user';
class User extends BaseUser {
api // Instance of Vuex api method
dirty // Whether the values have changed since last saved
constructor (data, client) {
super (data);
if (client) {
this.api = client;
} else if (data instanceof User) {
this.api = data.api;
}
this.dirty = false;
this.on("changed", () => this.dirty = true);
}
static async fromAPI (api, id) {
if (id) {
const url = `/user/${id}`;
const res = await api([url]);
return new User(res, api);
} else {
const url = `/user`;
const res = await api([url]);
return res?.map( row => new User(row, api) );
}
}
/** Save this user to the server
*
* If this is a new user, the `api` parameter must be
* supplied and this will result in a `POST` request.
* For an existing user coming from the database,
* `this.api` will be used for a `PUT` request.
*/
async save (api) {
if (this.api) {
const url = `/user/${this.id}`;
const init = {
headers: {
"Content-Type": "application/json"
},
method: "PUT",
body: this.toJSON()
};
const res = await this.api([url, init]);
if (res) {
this.dirty = false;
return new User(res, this.api);
} else {
// Something has gone wrong
console.log("Something has gone wrong (PUT)");
}
} else if (api) {
const url = `/user`;
const init = {
headers: {
"Content-Type": "application/json"
},
method: "POST",
body: this.toJSON()
}
const res = await api([url, init]);
if (res) {
return new User(res, api);
} else {
// Something has gone wrong
console.log("Something has gone wrong (POST)");
}
} else {
throw new Error("Don't know how to save this user");
}
}
/** Delete this user from the server
*/
async remove () {
const url = `/user/${this.id}`;
const init = {
headers: {
"Content-Type": "application/json"
},
method: "PUT",
body: this.toJSON()
};
const res = await this.api([url, init]);
console.log("remove RES", res);
}
}
export default User;