84 lines
2.7 KiB
JavaScript
84 lines
2.7 KiB
JavaScript
import { Client, Databases, Account, Query } from "appwrite";
|
|
import { DateTime } from "luxon";
|
|
|
|
class AppwriteService {
|
|
databaseId = 'lifetracker-db';
|
|
collectionId = "ryan";
|
|
constructor() {
|
|
this.appwrite = new Client().setEndpoint("http://ryanpandya.com:8080/v1").setProject("lifetracker")
|
|
this.database = new Databases(this.appwrite);
|
|
this.account = new Account(this.appwrite);
|
|
}
|
|
|
|
subscribe = (callback) => {
|
|
return this.appwrite.subscribe('databases.lifetracker-db.collections.ryan.documents', callback);
|
|
// "databases.${this.databaseId}.collections.${this.collectionId}.documents", callback);
|
|
}
|
|
|
|
addEntry = async ({ date, hours, mood, comments }) => {
|
|
await this.database.createDocument(this.databaseId, this.collectionId,
|
|
date,
|
|
{ date: new Date(date), hours: hours, mood: mood, comments: comments });
|
|
}
|
|
|
|
deleteEntry = async (entryId) => {
|
|
await this.database.deleteDocument(this.databaseId, this.collectionId, entryId);
|
|
}
|
|
|
|
updateEntry = async ({ date, hours, mood, comments }) => {
|
|
var hours = JSON.parse("[" + hours + "]")
|
|
await this.database.updateDocument(this.databaseId, this.collectionId,
|
|
date,
|
|
{ date: new Date(date), hours: hours, mood: mood, comments: comments });
|
|
}
|
|
|
|
getUser = async () => {
|
|
return await this.account.get();
|
|
}
|
|
|
|
login = async () => {
|
|
await this.account.createAnonymousSession();
|
|
return await this.getUser();
|
|
}
|
|
|
|
getEntries = async (date=null, numEntries=null) => {
|
|
if(date == null){
|
|
date = DateTime.fromObject({
|
|
year: DateTime.now().toFormat("y"),
|
|
month: 1,
|
|
day: 2
|
|
});
|
|
}
|
|
else{
|
|
date = DateTime.fromISO(date);
|
|
}
|
|
|
|
var firstEntry = (await this.database.listDocuments(
|
|
this.databaseId, this.collectionId,
|
|
[Query.orderAsc("date"),Query.limit(1)])
|
|
).documents[0];
|
|
var referenceDate = DateTime.fromISO(firstEntry.date).toUTC();
|
|
|
|
var offset = Math.floor(date.diff(referenceDate).as("days")) - 1;
|
|
|
|
if (numEntries == null) {
|
|
numEntries = Math.floor(DateTime.now().diff(referenceDate).as("days")) + 7;
|
|
}
|
|
|
|
return (await this.database.listDocuments(
|
|
this.databaseId, this.collectionId,
|
|
[
|
|
Query.orderAsc("date"),
|
|
Query.offset(offset),
|
|
Query.limit(numEntries)
|
|
]
|
|
)
|
|
).documents;
|
|
}
|
|
|
|
logout = () => {
|
|
return this.appwrite.account.deleteSession('current');
|
|
}
|
|
}
|
|
|
|
export default new AppwriteService() |