Initial Commit
This commit is contained in:
88
src/routes/orders.ts
Normal file
88
src/routes/orders.ts
Normal file
@@ -0,0 +1,88 @@
|
||||
import type { Debugger as Debug } from 'debug';
|
||||
import type { RouteOptions, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { Engine } from '@xo-cash/engine'
|
||||
import type { Database } from '../services/database/database.js'
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
export type OrdersRouteDeps = {
|
||||
database: Database;
|
||||
engine: Engine
|
||||
debug: Debug;
|
||||
}
|
||||
|
||||
export class OrdersRoute {
|
||||
public constructor(private readonly deps: OrdersRouteDeps) {}
|
||||
|
||||
public async getRoutes(): Promise<Array<RouteOptions>> {
|
||||
return [
|
||||
{
|
||||
method: 'GET',
|
||||
url: '/orders',
|
||||
handler: this.getOrders.bind(this),
|
||||
},
|
||||
{
|
||||
method: 'POST',
|
||||
url: '/orders',
|
||||
handler: this.createOrder.bind(this),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
private async getOrders(request: FastifyRequest, reply: FastifyReply) {
|
||||
// Get all orders from the database.
|
||||
const orders = await this.deps.database.db.selectFrom('orders').selectAll().execute();
|
||||
|
||||
// Return the orders.
|
||||
return reply.send(orders);
|
||||
}
|
||||
|
||||
private async createOrder(request: FastifyRequest, reply: FastifyReply) {
|
||||
// Parse the request body.
|
||||
const { items: itemsInput } = OrdersRoute.createOrderSchema.parse(request.body);
|
||||
|
||||
// Get the items from the database.
|
||||
const items = await this.deps.database.db.selectFrom('items').where('id', 'in', itemsInput.map((item) => item.id)).selectAll().execute();
|
||||
|
||||
// If the items are not found, return a 404 error.
|
||||
if (items.length !== items.length) {
|
||||
return reply.status(404).send({
|
||||
error: 'Items not found'
|
||||
});
|
||||
}
|
||||
|
||||
// TODO: Create an XO Engine Invitation with the relavent data in it so we can pass it back to the client.
|
||||
|
||||
// Create the order in the database.
|
||||
const order = await this.deps.database.db.insertInto('orders').values({
|
||||
// user_id: request.user.id,
|
||||
status: 'pending',
|
||||
total_price: 0,
|
||||
total_quantity: 0,
|
||||
items: JSON.stringify(items.map((item) => ({
|
||||
id: item.id,
|
||||
quantity: item.quantity,
|
||||
}))),
|
||||
}).execute();
|
||||
|
||||
// If the order is not created, return a 500 error.
|
||||
if (!order) {
|
||||
return reply.status(500).send({
|
||||
error: 'Failed to create order'
|
||||
});
|
||||
}
|
||||
|
||||
// Return the order.
|
||||
return reply.send(order);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schema for creating an order.
|
||||
*/
|
||||
static createOrderSchema = z.object({
|
||||
items: z.array(z.object({
|
||||
id: z.string(),
|
||||
quantity: z.number(),
|
||||
})),
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user