Skip to content

Commit

Permalink
Merge pull request #20 from thebedigupta/feature/local-storage-profil…
Browse files Browse the repository at this point in the history
…e-management

feat: implement local storage for user profile management
  • Loading branch information
devsdenepal authored Nov 5, 2024
2 parents 616cd4f + 286d365 commit d085ca0
Showing 1 changed file with 97 additions and 10 deletions.
107 changes: 97 additions & 10 deletions src/lib/appwrite.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,100 @@
import { Client, Account} from 'appwrite';
// localStorageService.js

export const client = new Client();
export const ID = {
unique: () => crypto.randomUUID()
};

client
.setEndpoint('https://cloud.appwrite.io/v1')
.setProject('670c108e0028ae3f4cf3'); // Replace with your project ID
class StorageClient {
constructor() {
this.endpoint = 'localStorage';
this.project = null;
}

export const account = new Account(client);
export const project_id = "670c108e0028ae3f4cf3";
export const database_id = "10927224";
export const collection_id = "670c12390011df38ec18"
export { ID } from 'appwrite';
setEndpoint(endpoint) {
this.endpoint = endpoint;
return this;
}

setProject(project) {
this.project = project;
return this;
}
}

class StorageAccount {
constructor(client) {
this.client = client;
this.USERS_KEY = 'users';
this.CURRENT_USER_KEY = 'currentUser';
}

async create(userId, email, password) {
try {
const users = this.#getUsers();
if (users.find(u => u.email === email)) {
throw new Error('User already exists');
}

const user = {
$id: userId || ID.unique(),
email,
password,
createdAt: new Date().toISOString()
};

users.push(user);
localStorage.setItem(this.USERS_KEY, JSON.stringify(users));
return user;
} catch (error) {
return Promise.reject(error);
}
}

async createEmailSession(email, password) {
try {
const users = this.#getUsers();
const user = users.find(u => u.email === email && u.password === password);

if (!user) {
throw new Error('Invalid credentials');
}

localStorage.setItem(this.CURRENT_USER_KEY, JSON.stringify(user));
return user;
} catch (error) {
return Promise.reject(error);
}
}

async get() {
try {
const user = localStorage.getItem(this.CURRENT_USER_KEY);
if (!user) {
throw new Error('User not found');
}
return JSON.parse(user);
} catch (error) {
return Promise.reject(error);
}
}

async deleteSession(sessionId) {
try {
localStorage.removeItem(this.CURRENT_USER_KEY);
return { status: 'success' };
} catch (error) {
return Promise.reject(error);
}
}

#getUsers() {
const users = localStorage.getItem(this.USERS_KEY);
return users ? JSON.parse(users) : [];
}
}

export const client = new StorageClient();
export const account = new StorageAccount(client);
export const project_id = "local-storage-project";
export const database_id = "local-storage-db";
export const collection_id = "local-storage-collection";

0 comments on commit d085ca0

Please sign in to comment.