Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • bhrotovy/lab-skeleton
  • datanass/lab-skeleton
  • zj5liu/se464-lab1
  • k25gu/lab-skeleton
  • ranwar/lab-skeleton
  • a36yadav/lab-skeleton-aka
  • pkolhe/se-464-lab-1
  • t442zhan/mint-gum
  • fkhoubsi/lab-skeleton
  • jems/lab-1
  • l39fu1/se-464-lab-skeleton
  • j44shah/lab-skeleton
  • se464-f23/lab-skeleton
13 results
Show changes
Commits on Source (25)
# AWS RDS
RDS_HOSTNAME=
RDS_USERNAME=
RDS_PASSWORD=
RDS_PORT=
RDS_DATABASE=
# AWS DYNAMODB
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=
\ No newline at end of file
# .env
.env
# Logs
logs
*.log
......
const db = process.argv[3];
const {
init,
queryRandomProduct,
queryUserById,
queryAllProducts,
queryProductById,
queryAllCategories,
queryAllOrders,
queryOrdersByUser,
queryOrderById,
queryAllUsers,
insertOrder,
updateUser,
} = require(db === "dynamo"
? "./dynamo_db.js"
: db === "sql"
? "./mysql_db.js"
: "");
const getRandomProduct = async (req, res) => {
const randProd = await queryRandomProduct();
res.send(randProd);
};
const getProduct = async (req, res) => {
const { productId } = req.params;
const product = await queryProductById(productId);
res.send(product);
};
const getProducts = async (req, res) => {
const { category } = req.query;
const products = await queryAllProducts(category);
res.send(products);
};
const getCategories = async (req, res) => {
const categories = await queryAllCategories();
res.send(categories);
};
const getAllOrders = async (req, res) => {
const orders = await queryAllOrders();
res.send(orders);
};
const getOrdersByUser = async (req, res) => {
const { userId } = req.query;
const orders = await queryOrdersByUser(userId);
res.send(orders);
};
const getOrder = async (req, res) => {
const { orderId } = req.params;
const order = await queryOrderById(orderId);
res.send(order);
};
const getUser = async (req, res) => {
const { userId } = req.params;
const user = await queryUserById(userId);
res.send(user);
};
const getUsers = async (req, res) => {
const users = await queryAllUsers();
res.send(users);
};
///TODO: Implement controller for POST /orders here
const patchUser = async (req, res) => {
const updates = req.body;
const { userId } = req.params;
const response = await updateUser(userId, updates);
res.send(response);
};
module.exports = {
init,
getProduct,
getRandomProduct,
getCategories,
getAllOrders,
getOrdersByUser,
getOrder,
getProducts,
getUser,
getUsers,
///TODO: Export controller for POST /orders,
patchUser,
};
require("dotenv").config();
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const {
GetCommand,
ScanCommand,
PutCommand,
UpdateCommand,
DynamoDBDocumentClient,
} = require("@aws-sdk/lib-dynamodb");
const uuid = require("uuid");
let client;
let docClient;
const init = () => {
client = new DynamoDBClient({ region: process.env.AWS_REGION });
docClient = DynamoDBDocumentClient.from(client);
console.log("DynamoDB connected!");
};
const queryRandomProduct = async () => {
///TODO: IMPLEMENT THIS
};
const queryProductById = async (productId) => {
const command = new GetCommand({
TableName: "Products",
Key: {
id: productId,
},
});
const response = await docClient.send(command);
return response.Item;
};
const queryAllProducts = async (category = "") => {
///TODO: Implement this
};
const queryAllCategories = async () => {
const command = new ScanCommand({
TableName: "Categories",
});
const response = await docClient.send(command);
return response.Items;
};
const queryAllOrders = async () => {
const command = new ScanCommand({
TableName: "Orders",
});
const response = await docClient.send(command);
return response.Items;
};
const queryOrdersByUser = async (userId) => {
const command = new ScanCommand({
TableName: "Orders",
FilterExpression: "user_id = :user_id",
ExpressionAttributeValues: {
":user_id": userId,
},
});
const response = await docClient.send(command);
return response.Items;
};
const queryOrderById = async (userId) => {
const command = new GetCommand({
TableName: "Orders",
Key: {
id: userId,
},
});
const response = await docClient.send(command);
return response.Item;
};
const queryUserById = async (userId) => {
const command = new GetCommand({
TableName: "Users",
Key: {
id: userId,
},
ProjectionExpression: "id, email",
});
const response = await docClient.send(command);
return response.Item;
};
const queryAllUsers = async () => {
const command = new ScanCommand({
TableName: "Users",
});
const response = await docClient.send(command);
return response.Items;
};
const insertOrder = async (order) => {
///TODO: Implement this
};
const updateUser = async (id, updates) => {
///TODO: Implement this
};
module.exports = {
init,
queryRandomProduct,
queryProductById,
queryAllProducts,
queryAllCategories,
queryAllOrders,
queryOrderById,
queryOrdersByUser,
queryUserById,
queryAllUsers,
insertOrder,
updateUser,
};
const db = process.argv[3];
const PROTO_PATH = "./app.proto";
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");
const {
init,
queryRandomProduct,
queryUserById,
queryAllProducts,
queryProductById,
queryAllCategories,
queryAllOrders,
queryOrdersByUser,
queryOrderById,
queryAllUsers,
insertOrder,
updateUser,
} = require(db === "dynamo"
? "./dynamo_db.js"
: db === "sql"
? "./mysql_db.js"
: "");
const { uuid } = require("uuidv4");
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const app = grpc.loadPackageDefinition(packageDefinition).App;
init();
async function randomProduct(call, callback) {
const randProd = await queryRandomProduct();
callback(null, randProd);
}
async function allProducts(call, callback) {
const products = await queryAllProducts();
callback(null, { products });
}
async function product(call, callback) {
const { product_id } = call.request;
const product = await queryProductById(product_id);
callback(null, product);
}
async function categories(call, callback) {
const categories = await queryAllCategories();
callback(null, { categories });
}
async function allOrders(call, callback) {
const orders = await queryAllOrders();
callback(null, { orders });
}
async function ordersByUser(call, callback) {
const { id } = call.request;
const orders = await queryOrdersByUser(id);
callback(null, { orders });
}
async function order(call, callback) {
const { order_id } = call.request;
const order = await queryOrderById(order_id);
callback(null, order);
}
async function user(call, callback) {
const { id } = call.request;
const user = await queryUserById(id);
callback(null, user);
}
async function users(call, callback) {
const users = await queryAllUsers();
callback(null, { users });
}
/// TODO: Implement postOrder here
async function accountDetails(call, callback) {
const { id } = call.request;
delete call.request.id;
const user = await updateUser(id, call.request);
callback(null, user);
}
/**
* Starts an RPC server that receives requests for the Greeter service at the
* sample server port
*/
const server = new grpc.Server();
server.addService(app.service, {
getRandomProduct: randomProduct,
getAllProducts: allProducts,
getProduct: product,
getAllCategories: categories,
getAllOrders: allOrders,
getAllUserOrders: ordersByUser,
getOrder: order,
getUser: user,
getAllUsers: users,
///TODO: add postOrder:
patchAccountDetails: accountDetails,
});
server.bindAsync(
"0.0.0.0:3001",
grpc.ServerCredentials.createInsecure(),
() => {
console.log("App ready and listening on port 3001");
server.start();
},
);
if (process.argv.length < 4) {
console.error("Not enough command line arguments!");
return;
}
const mode = process.argv[2];
if (mode === "rest") require("./restServer.js");
else if (mode === "grpc") require("./grpcServer.js");
require("dotenv").config();
const util = require("util");
const uuid = require("uuid");
const mysql = require("mysql2-promise")();
const init = async () => {
mysql.configure({
host: process.env.RDS_HOSTNAME,
user: process.env.RDS_USERNAME,
password: process.env.RDS_PASSWORD,
port: process.env.RDS_PORT,
database: process.env.RDS_DATABASE,
});
// try {
// await connect();
// console.log("Database connected!");
// } catch (e) {
// console.error(e);
// }
};
const queryProductById = async (productId) => {
return await mysql.query(`SELECT *
FROM products
WHERE id = "${productId}";`);
};
const queryRandomProduct = async () => {
///TODO: Implement this
};
const queryAllProducts = async () => {
///TODO: Implement this
};
const queryAllCategories = async () => {
return (await mysql.query("SELECT * FROM categories;"))[0];
};
const queryAllOrders = async () => {
return (await mysql.query("SELECT * FROM orders;"))[0];
};
const queryOrdersByUser = async (userId) => {
return (
await mysql.query(`SELECT *
FROM orders
INNER JOIN order_items ON orders.id = order_items.order_id
WHERE user_id = "${userId}"`)
)[0]; // Not a perfect analog for NoSQL, since SQL cannot return a list.
};
const queryOrderById = async (id) => {
return (
await mysql.query(`SELECT *
FROM orders
WHERE id = "${id}"`)
)[0][0];
};
const queryUserById = async (id) => {
return (
await mysql.query(`SELECT *
FROM users
WHERE id = "${id}";`)
)[0][0];
};
const queryAllUsers = async () => {
return (await mysql.query("SELECT * FROM users"))[0];
};
const insertOrder = async (order) => {
///TODO: Implement this
};
const updateUser = async (id, updates) => {
///TODO: Implement this
};
module.exports = {
init,
queryRandomProduct,
queryProductById,
queryAllProducts,
queryAllCategories,
queryAllOrders,
queryOrderById,
queryOrdersByUser,
queryUserById,
queryAllUsers,
insertOrder,
updateUser,
};
This diff is collapsed.
......@@ -2,10 +2,11 @@
"name": "lab-1-skeleton",
"version": "1.0.0",
"description": "Skeleton code for SE464 lab 1",
"main": "app.js",
"main": "dist/main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node main.js"
"compile": "tsc",
"start": "tsc && node dist/main.js"
},
"author": "based-jaml",
"license": "ISC",
......@@ -14,15 +15,27 @@
"@aws-sdk/client-s3": "^3.359.0",
"@aws-sdk/lib-dynamodb": "^3.352.0",
"@grpc/grpc-js": "^1.9.0",
"@grpc/proto-loader": "^0.7.8",
"@grpc/proto-loader": "^0.7.10",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.1.4",
"express": "^4.18.2",
"google-protobuf": "^3.21.2",
"long": "^5.2.3",
"morgan": "^1.10.0",
"mysql2": "^3.3.5",
"mysql2-promise": "^0.1.4",
"nice-grpc": "^2.1.7",
"protobufjs": "^7.2.6",
"typescript": "^5.3.3",
"uuidv4": "^6.2.13"
},
"devDependencies": {
"@types/body-parser": "^1.19.5",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/morgan": "^1.9.9",
"grpc-tools": "^1.12.4",
"ts-proto": "^1.167.1"
}
}
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const app = express();
const port = 3000;
app.use(cors());
app.use(morgan("tiny"));
app.use(bodyParser.json());
const {
init,
getProduct,
getRandomProduct,
getProducts,
getCategories,
getAllOrders,
getOrdersByUser,
getOrder,
getUser,
getUsers,
///TODO: Write controller function for POST /orders,
patchUser,
} = require("./controller.js");
init();
app.get("/", (req, res) => res.send("Hello, World!"));
app.get("/product/:productId", getProduct); // Gets a product by product id
app.get("/randomproduct", getRandomProduct); // I'm feeling lucky type
app.get("/products", getProducts); // Gets all products, or by category
app.get("/categories", getCategories); // Gets all categories
app.get("/allorders", getAllOrders);
app.get("/orders", getOrdersByUser); // Gets all of a single user's orders
app.get("/order/:orderId", getOrder); // Gets more details on a specific order by id
app.get("/user/:userId", getUser); // Gets details on a specific user by username
app.get("/users", getUsers);
///TODO: Implement POST /orders for order creation
app.patch("/user/:userId", patchUser);
app.listen(port, () => {
console.log(`App ready and listening on port ${port}`);
});
This diff is collapsed.
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { IDatabase } from "../interfaces";
import { GetCommand, ScanCommand, PutCommand, UpdateCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
import { Category, Order, Product, User, UserPatchRequest } from "../types";
export default class DynamoDB implements IDatabase {
docClient: DynamoDBDocumentClient;
constructor() {
const client = new DynamoDBClient({ region: process.env.AWS_REGION });
this.docClient = DynamoDBDocumentClient.from(client);
console.log("DynamoDB connected!");
};
async queryRandomProduct() {
///TODO: Implement this--replace the line below
return new Promise<Product>(() => { });
};
async queryProductById(productId: string) {
const command = new GetCommand({
TableName: "Products",
Key: {
id: productId,
},
});
const response = await this.docClient.send(command);
return response.Item as Product;
};
async queryAllProducts(category?: string) {
///TODO: Implement this--replace the line below
return new Promise<Product[]>(() => { });
};
async queryAllCategories() {
const command = new ScanCommand({
TableName: "Categories",
});
const response = await this.docClient.send(command);
return response.Items as Category[];
};
async queryAllOrders() {
const command = new ScanCommand({
TableName: "Orders",
});
const response = await this.docClient.send(command);
return response.Items as Order[];
};
async queryOrdersByUser(userId) {
const command = new ScanCommand({
TableName: "Orders",
FilterExpression: "userId = :userId",
ExpressionAttributeValues: {
":userId": userId,
},
});
const response = await this.docClient.send(command);
return response.Items as Order[];
};
async queryOrderById(userId) {
const command = new GetCommand({
TableName: "Orders",
Key: {
id: userId,
},
});
const response = await this.docClient.send(command);
return response.Item as Order;
};
async queryUserById(userId) {
const command = new GetCommand({
TableName: "Users",
Key: {
id: userId,
},
ProjectionExpression: 'id, #n, email',
ExpressionAttributeNames: { "#n": "name" },
});
const response = await this.docClient.send(command);
return response.Item as User;
};
async queryAllUsers() {
const command = new ScanCommand({
TableName: "Users",
ProjectionExpression: 'id, #n, email',
ExpressionAttributeNames: { "#n": "name" },
});
const response = await this.docClient.send(command);
return response.Items as User[];
};
async insertOrder(order: Order): Promise<void> {
///TODO: Implement this--replace the line below
return new Promise<void>(() => { });
}
async updateUser(patch: UserPatchRequest): Promise<void> {
///TODO: Implement this--replace the line below
return new Promise<void>(() => { });
};
};
\ No newline at end of file
import { Product } from "../compiled_proto/app";
import { IDatabase } from "../interfaces";
import { Category, Order, User, UserPatchRequest } from "../types";
import mysql from "mysql2/promise";
export default class MySqlDB implements IDatabase {
connection: mysql.Connection;
async init() {
this.connection = await mysql.createConnection({
host: process.env.RDS_HOSTNAME,
user: process.env.RDS_USERNAME,
password: process.env.RDS_PASSWORD,
port: parseInt(process.env.RDS_PORT), // Convert port to a number
database: process.env.RDS_DATABASE,
});
console.log("MySQL connected!");
}
constructor() {
this.init();
}
async queryProductById(productId) {
return (await this.connection.query(`SELECT *
FROM products
WHERE id = "${productId}";`))[0][0] as Product;
};
async queryRandomProduct() {
///TODO: Implement this
return this.connection.query('') as unknown as Product;
};
queryAllProducts = async (category?: string) => {
///TODO: Implement this
return this.connection.query('') as unknown as Product[];
};
queryAllCategories = async () => {
return (await this.connection.query("SELECT * FROM categories;"))[0] as Category[];
};
queryAllOrders = async () => {
///TODO: Implement this
return (await this.connection.query(""))[0] as Order[];
};
async queryOrdersByUser(id: string) {
///TODO: Implement this
return (
await this.connection.query('')
)[0] as Order[]; // Not a perfect analog for NoSQL, since SQL cannot return a list.
};
queryOrderById = async (id: string) => {
return (
await this.connection.query(`SELECT *
FROM orders
WHERE id = "${id}"`)
)[0][0];
};
queryUserById = async (id: string) => {
return (
await this.connection.query(`SELECT id, email, name
FROM users
WHERE id = "${id}";`)
)[0][0];
};
queryAllUsers = async () => {
return (await this.connection.query("SELECT id, name, email FROM users"))[0] as User[];
};
insertOrder = async (order: Order) => {
///TODO: Implement this
};
updateUser = async (patch: UserPatchRequest) => {
///TODO: Implement this
};
};
\ No newline at end of file
import { ProductRequest, Product, Order, OrderProduct, Category, UserRequest, UserPatchRequest, User } from './types';
export interface IDatabase {
queryRandomProduct(): Promise<Product>;
queryUserById(id: string): Promise<User>;
queryAllProducts(category?: string): Promise<Product[]>;
queryProductById(productId: string): Promise<Product>;
queryAllCategories(): Promise<Category[]>;
queryAllOrders(): Promise<Order[]>;
queryOrdersByUser(id: string): Promise<Order[]>;
queryOrderById(id: string): Promise<Order>;
queryAllUsers(): Promise<User[]>;
insertOrder(order: Order): Promise<void>;
updateUser(patch: UserPatchRequest): Promise<void>;
};
export interface IServer {
server: any;
db: IDatabase;
start(): void;
}
\ No newline at end of file
import dotenv from "dotenv";
import DynamoDB from "./dbs/dynamo_db";
import MySqlDB from "./dbs/mysql_db";
import { IDatabase, IServer } from "./interfaces";
import GrpcServer from "./servers/grpcServer";
import RestServer from "./servers/restServer";
if (process.argv.length < 4) {
console.error("Not enough command line arguments!");
throw new Error("Not enough command line arguments!");
}
dotenv.config();
const db_choice = process.argv[3];
let db: IDatabase;
switch (db_choice) {
case "dynamo":
db = new DynamoDB();
break;
case "mysql":
db = new MySqlDB();
break;
default:
console.error("Invalid database choice! (Must be dynamo or mysql)");
throw new Error("Invalid database choice! (Must be dynamo or mysql)");
}
const server_choice = process.argv[2];
let server: IServer;
switch (server_choice) {
case "rest":
server = new RestServer(db);
break;
case "grpc":
server = new GrpcServer(db);
break;
default:
console.error("Invalid server choice! (Must be rest or grpc)");
throw new Error("Invalid server choice! (Must be rest or grpc)");
}
server.start();
......@@ -5,7 +5,7 @@ service App {
rpc GetRandomProduct (EmptyRequest) returns (Product) {}
rpc GetAllProducts (EmptyRequest) returns (Products) {}
rpc GetAllProducts (AllProductsRequest) returns (Products) {}
rpc GetAllCategories (EmptyRequest) returns (Categories) {}
......@@ -28,13 +28,16 @@ message EmptyRequest {}
// Products
message AllProductsRequest {
optional string category_id = 1;
}
message ProductRequest {
string product_id = 1;
}
message Product {
string category_id = 1;
string images = 2;
int64 stock = 3;
int64 price = 4;
string description = 5;
......@@ -74,8 +77,7 @@ message Orders {
message Category {
string description = 1;
string id = 2;
int64 price = 3;
string name = 4;
string name = 3;
}
message Categories {
......@@ -96,6 +98,7 @@ message UserPatchRequest {
message User {
string id = 1;
string email = 2;
string name = 3;
}
message Users {
......
import {
AppDefinition,
AppServiceImplementation,
UserRequest,
EmptyRequest,
OrderRequest,
ProductRequest,
UserPatchRequest,
AllProductsRequest,
Order,
Orders,
Product,
Products,
Categories,
User,
Users,
DeepPartial,
} from '../compiled_proto/app';
import { IDatabase, IServer } from '../interfaces';
import { createServer } from 'nice-grpc';
class GrpcServiceImpl implements AppServiceImplementation {
db: IDatabase;
constructor(db: IDatabase) {
this.db = db;
}
async getProduct(request: ProductRequest): Promise<DeepPartial<Product>> {
const product = await this.db.queryProductById(request.productId);
return product;
}
async getRandomProduct(request: EmptyRequest): Promise<DeepPartial<Product>> {
const product = await this.db.queryRandomProduct();
return product;
}
async getAllProducts(request: AllProductsRequest): Promise<DeepPartial<Products>> {
const products = await this.db.queryAllProducts(request.categoryId);
return { products };
}
async getAllCategories(request: EmptyRequest): Promise<DeepPartial<Categories>> {
const categories = await this.db.queryAllCategories();
return { categories };
}
async getAllOrders(request: EmptyRequest): Promise<DeepPartial<Orders>> {
const orders = await this.db.queryAllOrders();
return { orders };
}
async getAllUserOrders(request: UserRequest): Promise<DeepPartial<Orders>> {
const orders = await this.db.queryOrdersByUser(request.id);
return { orders };
}
async getOrder(request: OrderRequest): Promise<DeepPartial<Order>> {
const order = await this.db.queryOrderById(request.id);
return order;
}
async getUser(request: UserRequest): Promise<DeepPartial<User>> {
const user = await this.db.queryUserById(request.id);
return user;
}
async getAllUsers(request: EmptyRequest): Promise<DeepPartial<Users>> {
const users = await this.db.queryAllUsers();
return { users };
}
async postOrder(request: Order): Promise<DeepPartial<Order>> {
await this.db.insertOrder(request);
return request;
}
async patchAccountDetails(request: UserPatchRequest): Promise<DeepPartial<User>> {
await this.db.updateUser(request);
const user = await this.db.queryUserById(request.id);
return user;
}
};
export default class GrpcServer implements IServer {
server: any;
db: IDatabase
constructor(db: IDatabase) {
this.db = db;
this.server = createServer();
}
async start() {
const port = 3001;
this.server.add(AppDefinition, new GrpcServiceImpl(this.db));
await this.server.listen(`0.0.0.0:${port}`);
console.log(`gRPC server listening on port ${port}`);
}
};
\ No newline at end of file
import { IDatabase, IServer } from "../interfaces";
import express from "express";
import cors from "cors";
import morgan from "morgan";
import bodyParser from "body-parser";
import { AllProductsRequest, Order, OrderRequest, ProductRequest, UserPatchRequest, UserRequest } from "../types";
export default class RestServer implements IServer {
db: IDatabase;
server: any;
constructor(db: IDatabase) {
this.db = db;
this.server = express();
}
start() {
const port = 3000;
this.server.use(cors());
this.server.use(morgan("tiny"));
this.server.use(bodyParser.json());
this.server.get("/", (req: express.Request, res: express.Response) => res.send("Hello, World!"));
this.server.get("/product/:productId", async (req: express.Request, res: express.Response) => {
const { productId } = (req.params as ProductRequest);
if (!productId) {
res.status(400).send("No product id provided");
return;
}
const product = await this.db.queryProductById(productId);
res.send(product);
}); // Gets a product by product id
this.server.get("/randomproduct", async (req: express.Request, res: express.Response) => {
const randProd = await this.db.queryRandomProduct();
res.send(randProd);
}); // I'm feeling lucky type
this.server.get("/products", async (req: express.Request, res: express.Response) => {
const { categoryId } = (req.query as AllProductsRequest);
const products = await this.db.queryAllProducts(categoryId);
res.send(products);
}); // Gets all products, or by category
this.server.get("/categories", async (req: express.Request, res: express.Response) => {
const categories = await this.db.queryAllCategories();
res.send(categories);
}); // Gets all categories
this.server.get("/allorders", async (req: express.Request, res: express.Response) => {
const orders = await this.db.queryAllOrders();
res.send(orders);
}); // Gets all orders
this.server.get("/orders", async (req: express.Request, res: express.Response) => {
const { id } = (req.query as UserRequest);
if (!id) {
res.status(400).send("No user id provided");
return;
}
const orders = await this.db.queryOrdersByUser(id);
res.send(orders);
}); // Gets all of a single user's orders
this.server.get("/order/:id", async (req: express.Request, res: express.Response) => {
const { id } = (req.params as OrderRequest);
if (!id) {
res.status(400).send("No order id provided");
return;
}
const order = await this.db.queryOrderById(id);
res.send(order);
}); // Gets more details on a specific order by id
this.server.get("/user/:id", async (req: express.Request, res: express.Response) => {
const { id } = (req.params as UserRequest);
if (!id) {
res.status(400).send("No user id provided");
return;
}
const user = await this.db.queryUserById(id);
res.send(user);
}); // Gets details on a specific user by username
this.server.get("/users", async (_req: express.Request, res: express.Response) => {
const users = await this.db.queryAllUsers();
res.send(users);
});// Gets all users
this.server.post("/orders", async (req: express.Request, res: express.Response) => {
const order = (req.body as Order);
const response = await this.db.insertOrder(order);
res.send(response);
}); // Creates a new order
this.server.patch("/user/:id", async (req: express.Request, res: express.Response) => {
const updates = req.body;
const userId = (req.params as UserRequest).id;
const patch: UserPatchRequest = {
...updates,
id: userId,
}
const response = await this.db.updateUser(patch);
res.send(response);
}); // Updates a user's email or password
this.server.listen(port, () => {
console.log(`REST server listening on port ${port}`);
});
}
}
export type ProductRequest = {
productId: string;
};
export type AllProductsRequest = {
categoryId: string;
}
export type Product = {
categoryId: string;
stock: number;
price: number;
description: string;
id: string;
name: string;
};
export type Order = {
userId: string;
id: string;
products: OrderProduct[];
totalAmount: number;
};
export type OrderRequest = {
id: string;
}
export type OrderProduct = {
productId: string;
quantity: number;
};
export type Category = {
description: string;
id: string;
name: string;
};
export type UserRequest = {
id: string;
};
export type UserPatchRequest = {
id: string;
email?: string;
password?: string;
}
export type User = {
id: string;
email: string;
name: string;
}
\ No newline at end of file
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
},
"include": [
"src/**/*"
],
"lib": [
"es2015"
]
}
\ No newline at end of file