· last year · Feb 08, 2025, 07:40 PM
1
2`index.ts:`
3import { Elysia } from "elysia";
4import { setupLoginRoute } from "./modules/users/auth/login";
5
6const app = new Elysia();
7
8// Define the root route
9app.get("/", () => "Hello Elysia");
10
11// Setup the login route
12setupLoginRoute(app);
13
14// Start the server
15const server = app.listen(3000);
16
17console.log(
18 `🦊 Elysia is running at ${server.server?.hostname}:${server.server?.port}, with endpoint: ${process.env.APPWRITE_ENDPOINT} - ${ process.env.APPWRITE_PROJECT_ID}`
19);
20
21`login.tx:`
22import { Elysia, t } from 'elysia';
23import { account } from '../../appwrite manager/appwrite';
24
25export function setupLoginRoute(app: Elysia) {
26 app.post(
27 '/login',
28 async ({ body }) => {
29 try {
30 const { email, password } = body;
31
32 // Validate input
33 if (!email || !password) {
34 return { error: 'Username and password are required' };
35 }
36
37 // Authenticate the user with Appwrite
38 await account.createEmailPasswordSession(email, password);
39
40 return { message: 'Login successful', user: email };
41 } catch (error: any) {
42 return { error: error.message || 'Invalid credentials' };
43 }
44 },
45 {
46 body: t.Object({
47 email: t.String(), // Username (or email) must be a string
48 password: t.String(), // Password must be a string
49 }),
50 }
51 );
52}
53
54`appwrite.ts:`
55import { Client, Databases, Storage, Users, Account } from 'node-appwrite';
56import * as dotenv from 'dotenv';
57
58// Load environment variables
59dotenv.config();
60
61// Initialize the Appwrite client with SSL configuration
62const client = new Client()
63 .setEndpoint(process.env.APPWRITE_ENDPOINT || '')
64 .setProject(process.env.APPWRITE_PROJECT_ID || '')
65 .setKey(process.env.APPWRITE_API_KEY || '')
66 .setSelfSigned(true);
67
68// Initialize Appwrite services
69export const databases = new Databases(client);
70export const storage = new Storage(client);
71export const users = new Users(client);
72export const account = new Account(client);
73