69 lines
1.6 KiB
TypeScript
69 lines
1.6 KiB
TypeScript
'use server';
|
|
|
|
import { db } from '@/db';
|
|
import { exchangeRates } from '@/db/schema';
|
|
import { eq } from 'drizzle-orm';
|
|
import { z } from 'zod';
|
|
|
|
const updateExchangeRateSchema = z.object({
|
|
from: z.string().min(1).max(10),
|
|
to: z.string().min(1).max(10),
|
|
rate: z.string().min(1),
|
|
});
|
|
|
|
export async function updateExchangeRate(
|
|
from: string,
|
|
to: string,
|
|
rate: string,
|
|
) {
|
|
const validation = updateExchangeRateSchema.safeParse({ from, to, rate });
|
|
if (!validation.success) {
|
|
return { success: false, error: 'Invalid input' };
|
|
}
|
|
|
|
try {
|
|
await db
|
|
.insert(exchangeRates)
|
|
.values({
|
|
fromCurrency: validation.data.from.toUpperCase(),
|
|
toCurrency: validation.data.to.toUpperCase(),
|
|
rate: validation.data.rate,
|
|
})
|
|
.onConflictDoUpdate({
|
|
target: [exchangeRates.fromCurrency, exchangeRates.toCurrency],
|
|
set: {
|
|
rate: validation.data.rate,
|
|
updatedAt: new Date(),
|
|
},
|
|
});
|
|
|
|
return { success: true };
|
|
} catch (error: unknown) {
|
|
if (
|
|
error &&
|
|
typeof error === 'object' &&
|
|
'code' in error &&
|
|
(error as { code: string }).code === '23505'
|
|
) {
|
|
return { success: false, error: 'Failed to update exchange rate' };
|
|
}
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function getExchangeRate(from: string, to: string) {
|
|
const result = await db
|
|
.select()
|
|
.from(exchangeRates)
|
|
.where(
|
|
eq(exchangeRates.fromCurrency, from.toUpperCase()),
|
|
)
|
|
.execute();
|
|
|
|
return result[0] || null;
|
|
}
|
|
|
|
export async function getAllExchangeRates() {
|
|
return db.select().from(exchangeRates).execute();
|
|
}
|