image picker, form

This commit is contained in:
echo committed 2025-02-10 20:28:38 +01:00
1 parent 7f702c58aa
commit f3007d6419
14 files changed
+757 -303

No files matched your search

+52 -38
View File
@@ -1,8 +1,9 @@
import {Account, Avatars, Client, Databases, OAuthProvider, Query} from "react-native-appwrite";
import { Account, Avatars, Client, Databases, OAuthProvider, Query } from "react-native-appwrite";
import * as Linking from "expo-linking"
import {openAuthSessionAsync} from "expo-web-browser";
import {attribute} from "postcss-selector-parser";
import { openAuthSessionAsync } from "expo-web-browser";
import { attribute } from "postcss-selector-parser";
import limit from "ajv-formats/src/limit";
import { Storage, ID } from 'react-native-appwrite';
// Add this debug log
// console.log('Environment Variables:', {
@@ -20,30 +21,31 @@ export const config = {
projectId: process.env.EXPO_PUBLIC_APPWRITE_PROJECT_ID,
databaseId: process.env.EXPO_PUBLIC_APPWRITE_DATABASE_ID,
usersId: process.env.EXPO_PUBLIC_APPWRITE_USERS_COLLECTION_ID,
// oglasuvacId: process.env.EXPO_PUBLIC_APPWRITE_OGLASUVAC_COLLECTION_ID,
// galleryId: process.env.EXPO_PUBLIC_APPWRITE_GALERIES_COLLECTION_ID,
// reviewId: process.env.EXPO_PUBLIC_APPWRITE_REVIEWS_COLLECTION_ID,
// vehicleId: process.env.EXPO_PUBLIC_APPWRITE_VEHICLE_COLLECTION_ID,
carId: process.env.EXPO_PUBLIC_APPWRITE_CARS_COLLECTION_ID,
bucketId: process.env.EXPO_PUBLIC_APPWRITE_BUCKET_ID,
}
export const client = new Client();
client
.setEndpoint(config.endpoint!)
.setProject(config.projectId!)
.setEndpoint(config.endpoint!)
.setProject(config.projectId!)
.setPlatform(config.platform!)
export const avatar = new Avatars(client);
export const account = new Account(client);
export const databases = new Databases(client);
export async function login (){
// Initialize storage
export const storageClient = new Storage(client);
export async function login() {
// Your code here to authenticate the user and return their JWT token.
try {
const redirectUri = Linking.createURL('/');
const response = await account.createOAuth2Token(OAuthProvider.Google, redirectUri);
if(!response) throw new Error('failed to login');
if (!response) throw new Error('failed to login');
const browserResult = await openAuthSessionAsync(
response.toString(),
@@ -59,12 +61,12 @@ export async function login (){
const secret = url.searchParams.get('secret')?.toString();
const userId = url.searchParams.get('userId')?.toString();
if (!secret ||!userId) {
if (!secret || !userId) {
throw new Error('failed to authenticate user');
}
const session = await account.createSession(userId, secret);
if (!session) throw new Error('failed to create session');
if (!session) throw new Error('failed to create session');
return true;
}
catch (error) {
@@ -76,7 +78,7 @@ export async function login (){
export async function getCurrentUser() {
try {
const response = await account.get();
if(response.$id){
if (response.$id) {
const userAvatar = avatar.getInitials(response.name)
return {
...response,
@@ -99,30 +101,6 @@ export async function logOut(): Promise<boolean> {
}
}
// export async function getData() {
// try {
// const result =await databases.listDocuments(
// config.databaseId!,
// config.vehicleId!,
// [Query.orderAsc(`$createdAt`), Query.limit(5)],
// )
// console.log(result.documents)
// return result.documents;
// }
// catch (error) {
// console.error("Failed to fetch data:", error);
// return [];
// }
// }
// export async function getVehicles({filter, query, limit}: {
// filter?: string;
// query?: string;
// limit?: number;
// }){
// }
export async function saveUserToDatabase(userData: {
userId: string;
@@ -161,3 +139,39 @@ export async function saveUserToDatabase(userData: {
return null;
}
}
// Add image upload function
export async function uploadImage(imageFile: {
uri: string;
name?: string;
type?: string;
size?: number;
}) {
try {
const response = await storageClient.createFile(
config.bucketId!,
ID.unique(),
{
uri: imageFile.uri,
name: imageFile.name || 'image.jpg',
type: imageFile.type || 'image/jpeg',
size: imageFile.size || 0
}
);
return storageClient.getFileView(config.bucketId!, response.$id).toString();
} catch (error) {
console.error('Error uploading image:', error);
throw error;
}
}
// Add image delete function
export async function deleteImage(fileId: string) {
try {
await storageClient.deleteFile(config.bucketId!, fileId);
return true;
} catch (error) {
console.error('Error deleting image:', error);
throw error;
}
}
+121
View File
@@ -0,0 +1,121 @@
import { databases, client, config } from './appwrite';
import { ID, Query } from 'react-native-appwrite'
// Car type based on your database schema
interface Car {
id: string;
title: string;
description: string;
price: number;
make: string;
model: string;
year: number;
fuelType: 'Petrol' | 'Diesel' | 'Electric' | 'Hybrid';
transmission: 'Manual' | 'Automatic';
location: string;
postedBy: string;
createdAt: string;
images: string[];
featured: boolean;
}
// Car functions
export async function createCar(carData: Omit<Car, 'id' | 'createdAt'>) {
try {
return await databases.createDocument(
config.databaseId!,
config.carId!,
ID.unique(),
{
...carData,
createdAt: new Date().toISOString(),
}
);
} catch (error) {
console.error('Error creating car:', error);
throw error;
}
}
export async function getCars() {
try {
const response = await databases.listDocuments(
config.databaseId!,
config.carId!,
[Query.orderDesc('$createdAt')]
);
return response.documents;
} catch (error) {
console.error('Error fetching cars:', error);
throw error;
}
}
export async function getFeaturedCars() {
try {
const response = await databases.listDocuments(
config.databaseId!,
config.carId!,
[
Query.orderDesc('$createdAt'),
Query.limit(5)
]
);
return response.documents;
} catch (error) {
console.error('Error fetching featured cars:', error);
throw error;
}
}
export async function getCar(id: string) {
try {
const response = await databases.getDocument(
config.databaseId!,
config.carId!,
id
);
return response;
} catch (error) {
console.error('Error fetching car:', error);
throw error;
}
}
// Favorites functions
export async function toggleFavorite(userId: string, carId: string) {
try {
const favorite = await databases.listDocuments(
config.databaseId!,
'favorites',
[
Query.equal('userId', userId),
Query.equal('carId', carId)
]
);
if (favorite.documents.length > 0) {
await databases.deleteDocument(
config.databaseId!,
'favorites',
favorite.documents[0].$id
);
return false; // Unfavorited
} else {
await databases.createDocument(
config.databaseId!,
'favorites',
ID.unique(),
{
userId,
carId,
createdAt: new Date().toISOString()
}
);
return true; // Favorited
}
} catch (error) {
console.error('Error toggling favorite:', error);
throw error;
}
}
+4 -4
View File
@@ -15,10 +15,10 @@ interface UseAppwriteReturn<T, P> {
}
export const useAppwrite = <T, P extends Record<string, string | number>>({
fn,
params = {} as P,
skip = false,
}: UseAppwriteOptions<T, P>): UseAppwriteReturn<T, P> => {
fn,
params = {} as P,
skip = false,
}: UseAppwriteOptions<T, P>): UseAppwriteReturn<T, P> => {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(!skip);
const [error, setError] = useState<string | null>(null);