Repository navigation
Expand file tree
/
Copy pathappwrite.ts
More file actions
78 lines (72 loc) · 1.94 KB
/
Copy pathappwrite.ts
File metadata and controls
78 lines (72 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { Utils } from '@nativescript/core';
import { Client, Account, Databases, ID } from '@nativescript/appwrite';
/**
* Set your own database ID and collection ID
*/
const DB_ID = '682e754400251b9879f8';
const COLLECTION_ID = '682e755b000ff5fd50f1';
export type MessageType = {
createdAt: string;
message: string;
};
export class AppwriteData {
client: Client;
account: Account;
database: Databases;
dataUpdates: (data: MessageType[]) => void;
constructor() {
this.client = new Client()
.setEndpoint(process.env.APP_WRITE_ENDPOINT)
.setProject(process.env.APP_WRITE_PROJECT_ID)
.setSelfSigned(true);
this.account = new Account(this.client);
this.database = new Databases(this.client);
}
async login(email: string, password: string): Promise<boolean> {
try {
const response = await this.account.createEmailPasswordSession(
email,
password
);
console.log('Logged in:', response);
this.database
.listDocuments(DB_ID, COLLECTION_ID)
.then((response: any) => {
console.log('Documents:', response);
if (this.dataUpdates) {
this.dataUpdates(
response.map((doc) => {
return {
createdAt: doc.createdAt,
message: doc.data.message,
};
})
);
}
});
return true;
} catch (error) {
console.error('Error logging in:', error);
}
return false;
}
async createDocument(data: any) {
const result = await this.database.createDocument(
DB_ID,
COLLECTION_ID,
crypto.randomUUID(),
data
);
console.log('Document created:', result);
if (this.dataUpdates) {
const data = Utils.dataDeserialize(result.data);
this.dataUpdates([
{
message: data.message,
createdAt: result.createdAt,
},
]);
}
return result;
}
}