feat: sync user on startup

This commit is contained in:
thecodrr
2020-05-23 17:20:24 +05:00
parent a7a1d3396a
commit 2e80859bea
2 changed files with 28 additions and 11 deletions

View File

@@ -32,6 +32,8 @@ class Database {
this._validate(); this._validate();
this.user = new User(this); this.user = new User(this);
await this.user.sync();
this.syncer = new Sync(this); this.syncer = new Sync(this);
this.vault = new Vault(this); this.vault = new Vault(this);
this.conflicts = new Conflicts(this); this.conflicts = new Conflicts(this);

View File

@@ -10,6 +10,14 @@ export default class User {
this._context = db.context; this._context = db.context;
} }
async sync() {
var user = await this.get();
if (!user) return;
user = await authRequest("users", undefined, true, true);
delete user.lastSynced;
await this.set(user);
}
get() { get() {
return this._context.read("user"); return this._context.read("user");
} }
@@ -29,14 +37,13 @@ export default class User {
async upgrade(refno) { async upgrade(refno) {
if (!refno) return; if (!refno) return;
await this.set({ refno, upgrading: true }); await this.set({ refno, upgrading: true });
const token = await this.token(); let response = await authRequest("upgrade", { refno }, true);
let response = await authRequest( if (response.duration) {
"upgrade", await this.set({
{ refno }, refno: undefined,
{ Authorization: `Bearer ${token}` } trialExpiryDate: response.duration,
); upgrading: undefined,
if (response.success) { });
await this.set({ refno: null, upgrading: false });
} }
} }
@@ -109,11 +116,19 @@ function userFromResponse(response, key) {
return user; return user;
} }
async function authRequest(endpoint, data, headers = {}) { async function authRequest(endpoint, data, auth = false, get = false) {
var headers = {};
if (auth) {
const token = await this.token();
headers = {
Authorization: `Bearer ${token}`,
};
}
let response = await fetch(`${HOST}${endpoint}`, { let response = await fetch(`${HOST}${endpoint}`, {
method: "POST", method: get ? "GET" : "POST",
headers: { ...HEADERS, ...headers }, headers: { ...HEADERS, ...headers },
body: JSON.stringify(data), body: get ? undefined : JSON.stringify(data),
}); });
if (response.ok) { if (response.ok) {