Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
535 changes: 525 additions & 10 deletions package-lock.json

Large diffs are not rendered by default.

21 changes: 20 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,36 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon src/app.ts",
"start": "nodemon src/server.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/cors": "^2.8.19",
"@types/express": "^5.0.3",
"@types/morgan": "^1.9.10",
"@types/multer": "^1.4.13",
"@types/node": "^24.0.1",
"express": "^5.1.0",
"ts-node": "^10.9.2",
"typescript": "^5.8.3"
},
"repository": {
"type": "git",
"url": "git+https://github.com/iPexzo/Task-Express-M2-noSQL-Banks-TS.git"
},
"type": "commonjs",
"bugs": {
"url": "https://github.com/iPexzo/Task-Express-M2-noSQL-Banks-TS/issues"
},
"homepage": "https://github.com/iPexzo/Task-Express-M2-noSQL-Banks-TS#readme",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.5.0",
"mongoose": "^8.15.2",
"morgan": "^1.10.0",
"multer": "^2.0.1"
}
}
34 changes: 17 additions & 17 deletions src/account.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
export const accounts = [
{
id: 1,
username: "Omar",
funds: 30,
},
{
id: 2,
username: "Zainab",
funds: 0,
},
{
id: 3,
username: "Salwa",
funds: 100,
},
];
const ccounts = [
{
id: 1,
username: "Omar",
funds: 30,
},
{
id: 2,
username: "Zainab",
funds: 0,
},
{
id: 3,
username: "Salwa",
funds: 100,
},
];
131 changes: 92 additions & 39 deletions src/api/accounts/accounts.controller.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,101 @@
import { Request, Response } from 'express';
import { accounts } from '../../account';
import { NextFunction, Request, Response } from "express";
import Account from "../../models/database";

export const accountCreate = (req: Request, res: Response) => {
const id = accounts[accounts.length - 1].id + 1;
const newAccount = { ...req.body, funds: 0, id };
accounts.push(newAccount);
res.status(201).json(newAccount);
//Get all account is working
export const accountsGet = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const allAccount = await Account.find();
res.status(200).json(allAccount);
} catch (error) {
next(error);
}
};

export const accountDelete = (req: Request, res: Response) => {
const { accountId } = req.params;
const foundAccount = accounts.find((account) => account.id === +accountId);
if (foundAccount) {
let newAccounts = accounts.filter((account) => account.id !== +accountId);
res.status(204).end();
} else {
res.status(404).json({ message: 'Account not found' });
// GET BY USER NAME WORKING
export const getAccountByUsername = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { username } = req.params;
const foundAccount = await Account.findOne({ username });
if (!foundAccount) {
res.status(404).json({ message: "Account not found" });
}
res.status(200).json(foundAccount);
} catch (error) {
next(error);
}
};

export const accountUpdate = (req: Request, res: Response) => {
// create account is working
export const accountCreate = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { username, funds, image } = req.body;
let imagePath;
console.log("image from file", req.file); // this for image info
if (req.file) {
imagePath = req.file.path;
}
// if (!username || funds === undefined) {
// res.status(400).json({ message: "username or funds are missing" });
// }
const addAccount = await Account.create({
username,
funds,
image: imagePath,
});
console.log("Mongodb create");
res.status(201).json(addAccount);
} catch (error) {
next(error);
}
};
// delete account is working
export const accountDelete = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { accountId } = req.params;
const foundAccount = accounts.find((account) => account.id === +accountId);
if (foundAccount) {
foundAccount.funds = req.body.funds;
res.status(204).end();
} else {
res.status(404).json({ message: 'Account not found' });
const foundAccount = await Account.findById(accountId);
if (!foundAccount) {
res.status(404).json({ message: "account not found" });
}
await Account.deleteOne({ _id: accountId });
// const getNewList = await Account.find();
res.status(200).json({
message: "Deleted successfully",
// data: getNewList,
});
} catch (error) {
next(error);
}
};
// update account is working
export const accountUpdate = async (
req: Request,
res: Response,
next: NextFunction
) => {
try {
const { accountId } = req.params;
const foundAccount = await Account.findById(accountId);
if (!foundAccount) {
res.status(404).json({ message: "account not found" });
}

export const accountsGet = (req: Request, res: Response) => {
res.json(accounts);
await Account.updateOne({ _id: accountId }, req.body);
res.status(204).end();
} catch (error) {
next(error);
}
};

export const getAccountByUsername = (req: Request, res: Response) => {
const { username } = req.params;
const foundAccount = accounts.find(
(account) => account.username === username
);
if (req.query.currency === 'usd' && foundAccount) {
const accountInUsd = { ...foundAccount, funds: foundAccount.funds * 3.31 };
res.status(201).json(accountInUsd);
} else {
res.status(201).json(foundAccount);
}
};
31 changes: 22 additions & 9 deletions src/api/accounts/accounts.routes.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
import express from 'express';
import express, { NextFunction, Request, Response } from "express";
const accountsRouter = express.Router();
import { accountsGet, accountUpdate, accountDelete, accountCreate, getAccountByUsername } from './accounts.controller';
import {
accountsGet,
accountUpdate,
accountDelete,
accountCreate,
getAccountByUsername,
} from "./accounts.controller";
import upload from "../../middlewares/multer";

accountsRouter.get('/', accountsGet);
accountsRouter.get('/:username', getAccountByUsername);
accountsRouter.post('/', accountCreate);
accountsRouter.get(
"/",
(req: Request, res: Response, next: NextFunction) => {
console.log("Getting all accounts");
next();
},
accountsGet
);
accountsRouter.post("/", upload.single("image"), accountCreate);

accountsRouter.delete('/:accountId', accountDelete);
accountsRouter.get("/:username", getAccountByUsername);
accountsRouter.delete("/:accountId", accountDelete);
accountsRouter.put("/:accountId", accountUpdate);

accountsRouter.put('/:accountId', accountUpdate);

export default accountsRouter;
export default accountsRouter;
43 changes: 37 additions & 6 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,43 @@
import express from "express";
import express, { NextFunction, Request, Response } from "express";
import accountsRouter from "./api/accounts/accounts.routes";
import morgan from "morgan";
import cors from "cors";
import { NotFoundHandler } from "./middlewares/NotFound";
import { ErrorHandler } from "./middlewares/ErrorHandler";

const app = express();
const PORT = 8000;
export const app = express();

app.use(express.json());
app.use(cors());

app.use(morgan("dev"));

app.use("/accounts", accountsRouter);

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
app.use(NotFoundHandler);
app.use(ErrorHandler);

// // this for rquest!
// app.use((req: Request, res: Response, next: NextFunction) => {
// console.log(
// "you recevied a request at this time: ",
// new Date().toISOString()
// );
// next();
// });

// //this for log for every request i get
// app.use((req: Request, res: Response, next: NextFunction) => {
// console.log(
// `You recived a request of type ${req.method} at the endpoint ${req.path}`,
// new Date().toLocaleString()
// );
// next();
// });
// app.use((req: Request, res: Response, next: NextFunction) => {
// res.status(404).json({ message: `404 - ${req.path} Not Found`, data: [] });
// });

// app.use((err: any, req: Request, res: Response, next: NextFunction) => {
// res.status(err.status).json(`something broke$ ${err}`);
// });
10 changes: 10 additions & 0 deletions src/middlewares/ErrorHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { NextFunction, Request, Response } from "express";

export const ErrorHandler = (
err: any,
req: Request,
res: Response,
next: NextFunction
) => {
res.status(err.status).json(`something broke$ ${err}`);
};
10 changes: 10 additions & 0 deletions src/middlewares/NotFound.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { NextFunction, Request, Response } from "express";
import { app } from "../app";

export const NotFoundHandler = (
req: Request,
res: Response,
next: NextFunction
) => {
res.status(404).json({ message: `404 - ${req.path} Not Found`, data: [] });
};
15 changes: 15 additions & 0 deletions src/middlewares/multer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import multer from "multer";

const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads"); // it will go to upload file any photos i will upload
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
cb(null, file.fieldname + "-" + uniqueSuffix + "-" + file.originalname);
},
});

const upload = multer({ storage: storage });

export default upload;
15 changes: 15 additions & 0 deletions src/models/database.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { model, Schema } from "mongoose";

const accountSchema = new Schema(
{
username: { type: String, required: true, unique: true },
funds: { type: Number, default: 0 },
image: { type: String },
},
{ timestamps: true }
);

// insinde model always should be without S becausee always insinde the app it will be with s automaticaly
const Account = model("account", accountSchema);

export default Account;
19 changes: 19 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { app } from "./app";
import mongoose from "mongoose";
import dotenv from "dotenv";

dotenv.config(); //this will expose env file
const connectDB = async () => {
try {
await mongoose.connect(process.env.DATABASE || "");
console.log(`connected to mongodb`);
} catch (error) {
console.log("mongodb error", error);
}
};

connectDB();

app.listen(8000, () => {
console.log("Server is running on Port 8000");
});
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added uploads/image-1750177741675-128971466-hello.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.