(Day 1) Project : BLOG
What's the Purpose of This Code?
This code is part of a system to manage user accounts. It does things like:
Creating a new account for a user (sign-up).
Logging in a user.
Checking who is logged in (current user).
Logging out a user.
It uses a service called Appwrite, which is a tool that helps manage these tasks behind the scenes.
What Does Each Part of the Code Do?
1. Importing Tools
import { Client, Account, ID } from "appwrite";
import conf from "../conf/conf";
Client, Account, ID: These are tools from Appwrite that help us interact with its services.
conf: This is a file where important information (like the Appwrite URL and project ID) is stored. Instead of writing this information everywhere in the code, we keep it in one place and use it wherever needed.
2. Creating a Class
export class AuthService {
client = new Client();
A class is like a blueprint to create objects. Here, the class
AuthService
is designed to handle user-related tasks (like signing up and logging in).client
is an instance of Client that connects to Appwrite.
3. Setting Up the Connection
constructor() {
this.client.setEndpoint(conf.appwriteUrl);
this.client.setProject(conf.appwriteProjectId);
this.account = new Account(this.client);
}
Constructor: This is a special function that runs automatically when we create an object from the class.
setEndpoint
: Tells the app where to find the Appwrite server (fromconf.appwriteUrl
).setProject
: Tells which Appwrite project to use (fromconf.appwriteProjectId
).this.account
: Creates an Account object to manage user accounts.
4. Creating an Account
async createAccount({ email, password, name }) {
try {
const userAccount = await this.account.create(ID.unique(), email, password, name);
if (userAccount) {
return this.login({ email, password });
} else {
return userAccount;
}
} catch (error) {
console.error(error);
throw error;
}
}
Purpose: Creates a new user account.
How It Works:
ID.unique()
: Generates a unique ID for the new user.this.account.create(...)
: Sends the user's email, password, and name to Appwrite to create the account.If the account is created, it directly logs the user in using the
login
method.
Why async and await? These make the program wait until the account creation is finished before moving to the next step.
5. Logging In
async login({ email, password }) {
try {
return await this.account.createEmailSession(email, password);
} catch (error) {
console.error(error);
throw error;
}
}
Purpose: Logs in a user.
How It Works: Checks the email and password with Appwrite. If correct, the user is logged in.
6. Getting the Current User
async getCurrentUser() {
try {
return await this.account.get();
} catch (error) {
console.error(error);
throw error;
}
return null;
}
Purpose: Finds out who is currently logged in.
How It Works: Asks Appwrite, "Who is logged in right now?" and returns the user details.
7. Logging Out
async logout() {
try {
await this.account.deleteSessions();
} catch (error) {
console.error(error);
throw error;
}
}
Purpose: Logs out the user.
How It Works: Deletes the user's session (like ending a login session).
8. Creating and Exporting an Object
const authService = new AuthService();
export default AuthService;
authService: An object made from the
AuthService
class. This object lets us use the methods (createAccount
,login
, etc.).export default AuthService: Makes the class reusable in other files.
Why Use This Code?
Organization: The code is well-organized in a class. It keeps all user-related actions in one place.
Reusability: By creating methods (
createAccount
,login
, etc.), we can easily reuse them in different parts of the app.Async Operations: The
async
functions make sure tasks like creating accounts or logging in are completed before the program moves forward.Error Handling: The
try...catch
blocks handle errors gracefully, making it easier to debug problems.
Flow of the Code
A user signs up using
createAccount
.If the account is created, the user is automatically logged in.
The app can check who is logged in using
getCurrentUser
.When the user is done, they can log out using
logout
.
***************************************************************************************
Notes on Using Appwrite
Set Up Environment Variables:
Get the Project ID and Endpoint from Appwrite.
Add them to the
.env
file for secure usage.
Create a Database:
Go to the Database section and create a new project.
Copy the Database ID.
Collections:
A database can have multiple Collections (similar to tables).
Example: Create a collection named Article and copy the Collection ID.
Set Permissions:
Go to Settings → Permissions.
Allow All Users to access the collection.
Restrict access to only registered users.
Attributes:
Add attributes to the collection in the Documents section.
Example: Add a
featuredImage
attribute to store the image ID as a string.
Indexes:
- Create Indexes in the collection for filtering and querying efficiently.
Storage (Bucket ID):
Create a Bucket in the Storage section to store images.
Copy the Bucket ID.
Set permissions in the bucket settings for access control.
Environment Variables and Configuration:
Create a
config.js
file in aconfig
folder to manage environment variables.Use
import.meta.env
to access environment variables, but note it may not always load correctly.
Appwrite Services:
Appwrite offers multiple services (e.g., Database, Authentication, Storage).
Export methods for each service for clean and modular usage.
Client Setup:
Create a Client for connecting to Appwrite.
Use the Account service to manage users.
Encryption:
- Appwrite handles encryption and security for sensitive data automatically.