function makeReservation(xona) {
return new Promise((res, rej) => {
if (xona) {
res("Buyurtma tasdiqlandi!");
} else {
rej("Kechirasiz, xonalar mavjud emas !");
}
});
}
makeReservation(true) // Argument sifatida true yozilsa resolve false yozilsa reject ishlaydi !
.then((data) => {
console.log(data);
})
.catch((e) => {
console.log(e);
});π₯4π2π2
// 2-usul
const h1 = document.createElement("h1");
document.body.appendChild(h1);
function cars() {
const ul = document.createElement("ul");
const li = document.createElement("li");
const h3 = document.createElement("h3");
const p = document.createElement("p");
const image = document.createElement("img");
image.src =
"https://imgd.aeplcdn.com/370x208/n/cw/ec/144851/exter-exterior-right-front-three-quarter-29.jpeg?isig=0&q=80";
h1.innerHTML = "Auto Salon";
h3.innerHTML = "Title";
p.innerHTML =
"Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla, ex.";
document.body.appendChild(ul);
ul.appendChild(li);
li.appendChild(h3);
li.appendChild(p);
li.appendChild(image);
}
cars();
cars();
cars();
cars();
const h2 = document.createElement("h2");
h2.innerHTML = "About Us";
document.body.appendChild(h2);
function names() {
const section = document.createElement("section");
document.body.appendChild(section);
const image = document.createElement("img");
image.src =
"https://imgd.aeplcdn.com/370x208/n/cw/ec/144851/exter-exterior-right-front-three-quarter-29.jpeg?isig=0&q=80";
section.appendChild(image);
}
names(), names(), names(), names();
β‘4π4π2
const url = require("node:url");
const uuid = require("uuid");
const http = require("node:http");
class ResponseData {
constructor(statusCode, message, data) {
this.statusCode = statusCode;
this.message = message;
this.data = data;
}
}
class Fruit {
constructor(name, price, count) {
this.id = uuid.v4();
this.name = name;
this.price = price;
this.count = count;
}
}
class Car {
constructor(model, price) {
this.id = uuid.v4();
this.model = model;
this.price = price;
}
}
const fruits = [];
const cars = [];
const server = http.createServer((req, res) => {
const [, moduleName, id] = url.parse(req.url).pathname.split("/");
const method = req.method;
if (method === "GET" && moduleName === "fruits" && !id) {
const response = new ResponseData(200, "Success", fruits);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
} else if (method === "GET" && moduleName === "cars" && !id) {
const response = new ResponseData(200, "Success", cars);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
// get fruits
} else if (method === "GET" && moduleName === "fruits" && id) {
const fruit = fruits.find((f) => f.id === id);
if (!fruit) {
const response = new ResponseData(404, "Fruit not found");
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
} else {
const response = new ResponseData(200, "Success", fruit);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
}
// get cars
} else if (method === "GET" && moduleName === "cars" && id) {
const car = cars.find((c) => c.id === id);
if (!car) {
const response = new ResponseData(404, "Car not found");
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
} else {
const response = new ResponseData(200, "Success", car);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
}
//fruitlarni delete qilish
} else if (method === "DELETE" && moduleName === "fruits" && id) {
const fruitIndex = fruits.findIndex((el) => el.id === id);
if (fruitIndex === -1) {
const response = new ResponseData(404, "Fruit not found!");
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
} else {
const deletedFruit = fruits.splice(fruitIndex, 1)[0];
const response = new ResponseData(200, "Fruit deleted", deletedFruit);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
}
//carlarni delete qilish
} else if (method === "DELETE" && moduleName === "cars" && id) {
const carIndex = cars.findIndex((el) => el.id === id);
if (carIndex === -1) {
const response = new ResponseData(404, "Car not found!");
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
} else {
const deletedCar = cars.splice(carIndex, 1)[0];
const response = new ResponseData(200, "Car deleted", deletedCar);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
}
// fruis post
} else if (method === "POST" && moduleName === "fruits") {
let reqData = "";
req.on("data", (chunk) => {
reqData = reqData + chunk.toString();
});
req.on("end", () => {
let body = {};
if (reqData.length) {
body = JSON.parse(reqData);
}
// body name stringligini tekshirish
if (typeof body.name !== "string") {
const response = new ResponseData(400, "Name must be a string!");
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
return;
}π₯2π2π1π1
//body count numberligini tekshirish
if (typeof body.count !== "number" || typeof body.price !== "number") {
const response = new ResponseData(
400,
"Count and price must be numbers!"
);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
return;
}
const newFruit = new Fruit(body.name, body.price, body.count);
fruits.push(newFruit);
const response = new ResponseData(201, "Created", newFruit);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
});
// cars post
} else if (method === "POST" && moduleName === "cars") {
let reqData = "";
req.on("data", (chunk) => {
reqData = reqData + chunk.toString();
});
req.on("end", () => {
let body = {};
if (reqData.length) {
body = JSON.parse(reqData);
}
// car modelni stringligini tekshirish
if (typeof body.model !== "string") {
const response = new ResponseData(400, "Model must be a string!");
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
return;
}
//cars price ni tekshirish
if (typeof body.price !== "number") {
const response = new ResponseData(400, "Price must be a number!");
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
return;
}
//..............
const newCar = new Car(body.model, body.price);
cars.push(newCar);
const response = new ResponseData(201, "Created", newCar);
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
});
} else {
const response = new ResponseData(404, "Not Found");
res.writeHead(response.statusCode);
res.end(JSON.stringify(response));
}
});
server.listen(3000, () => {
console.log("Server is running at http://localhost:3000");
});
β‘2π₯1π1πΏ1
186 qator kodπ€― (osonroq kasb qurib qolganmidiπ)
π2π€―2π₯1π1π¨βπ»1
bunisi 200 qator bo'lib ketdi π
π2π¨βπ»2π₯1π1
const http = require("node:http");
const url = require("node:url");
const { ResData } = require("./lib/resData");
const { Repository } = require("./lib/repository");
const path = require("node:path");
const { bodyParser } = require("./lib/bodyParser");
const { CategoryEntity } = require("./lib/categoryEntity");
const { Fruit } = require("./lib/fruit");
const { User } = require("./lib/user");
//for category
const categoryDir = path.join(__dirname, "database", "categories.json");
const categoryRepo = new Repository(categoryDir);
//for fruit
const fruitDir = path.join(__dirname, "database", "fruits.json");
const fruitRepo = new Repository(fruitDir);
//for user
const userDir = path.join(__dirname, "database", "user.json");
const userRepo = new Repository(userDir);
async function handleRequest(req, res) {
const method = req.method;
const parsedUrl = url.parse(req.url).pathname.split("/");
// ------------------ category get,post,delete --------------------------
// category get
if (method === "GET" && parsedUrl[1] === "category") {
const getAllData = await categoryRepo.read();
const resData = new ResData(200, "success", getAllData);
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
// category post
} else if (method === "POST" && parsedUrl[1] === "category") {
const body = await bodyParser(req);
if (!body.name) {
const resData = new ResData(400, "Please provide a name");
res.writeHead(resData.statusCode);
return res.end(JSON.stringify(resData));
}
const newCategory = new CategoryEntity(body.name, 0);
await categoryRepo.writeNewData(newCategory);
const resData = new ResData(201, "created", newCategory);
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
// category delete
} else if (
method === "DELETE" &&
parsedUrl[1] === "category" &&
parsedUrl[2]
) {
const id = parsedUrl[2];
const data = await categoryRepo.read();
const itemIndex = data.findIndex((item) => item.id === id);
if (itemIndex === -1) {
const resData = new ResData(404, "No object found with the given id");
res.writeHead(resData.statusCode);
return res.end(JSON.stringify(resData));
}
data.splice(itemIndex, 1);
await categoryRepo.write(data);
const resData = new ResData(200, "Deleted successfully");
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
// category put
} else if (method === "PUT" && parsedUrl[1] === "category" && parsedUrl[2]) {
const body = await bodyParser(req);
const id = parsedUrl[2];
const data = await categoryRepo.read();
const itemIndex = data.findIndex((item) => item.id === id);
if (itemIndex === -1) {
const resData = new ResData(404, "No object found with the given id");
res.writeHead(resData.statusCode);
return res.end(JSON.stringify(resData));
}
data[itemIndex].name = body.name;
await categoryRepo.write(data);
const resData = new ResData(200, "Updated successfully");
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
}
// -------------------Fruit get,post,delete,put-----------------------------
// fruit get
if (method === "GET" && parsedUrl[1] === "fruits") {
const getAllData = await fruitRepo.read();
const resData = new ResData(200, "success", getAllData);
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
// fruit post
} else if (method === "POST" && parsedUrl[1] === "fruits") {
const body = await bodyParser(req);
if (!body.name || !body.price || !body.count) {
const resData = new ResData(400, "Must be name,price,count");
res.writeHead(resData.statusCode);
return res.end(JSON.stringify(resData));
}
const newCategory = new Fruit(body.name, body.count, body.price);
await fruitRepo.writeNewData(newCategory);
const resData = new ResData(201, "created", newCategory);π₯1π€―1π1π¨βπ»1
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
// fruit delete
} else if (method === "DELETE" && parsedUrl[1] === "fruits" && parsedUrl[2]) {
const id = parsedUrl[2];
const data = await fruitRepo.read();
const itemIndex = data.findIndex((item) => item.id === id);
if (itemIndex === -1) {
const resData = new ResData(404, "No object found with the given id");
res.writeHead(resData.statusCode);
return res.end(JSON.stringify(resData));
}
data.splice(itemIndex, 1);
await fruitRepo.write(data);
const resData = new ResData(200, "Deleted successfully");
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
}
// -------------User get,post,delete----------------
// User get
if (method === "GET" && parsedUrl[1] === "user") {
const getAlldata = await userRepo.read();
const resData = ResData(200, "success", getAlldata);
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
// User post
} else if (method === "POST" && parsedUrl[1] === "user") {
const body = await bodyParser(req);
if (!body.name) {
const resData = ResData(400, "Must be name");
res.writeHead(resData.statusCode);
return res.end(JSON.stringify(resData));
}
const user = new User(body.name);
await userRepo.writeNewData(user);
const resData = new ResData(200, "created", user);
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
// User delete
} else if ((method === "DELETE", parsedUrl[1] === "user", parsedUrl[2])) {
const id = parsedUrl[2];
const data = await userRepo.read();
const findIndex = data.findIndex((item) => item.id === id);
if (findIndex === -1) {
const resData = new ResData(400, "No object found with the given id");
res.writeHead(resData.statusCode);
res.end(JSON.stringify(resData));
}
data.splice(itemIndex, 1);
await userRepo.write(data);
const resData = new ResData(200, "Deleted successfully");
res.writeHead(resData.statusCode);
res.end(json.stringify(resData));
}
}
const server = http.createServer(handleRequest);
server.listen(7777, () => {
console.log("http://localhost:7777");
});
// 200 qator kod π€―
π₯1π1π1π¨βπ»1
const express = require("express");
const cors = require("cors");
const app = express();
const port = 7777;
const { carCreateScheam, createUserScheam } = require("./scheams");
const axios = require("axios");
const cars = [
{
id: 1,
model: "Toyota",
},
{
id: 2,
model: "BMW",
},
];
app.use(cors());
app.use(express.json());
function getById(id) {
const foundCar = cars.findIndex((el) => el.id === id);
if (foundCar === -1) {
return undefined;
} else {
return foundCar;
}
}
// car get
app.get("/api/cars", (req, res) => {
res.status(200).json({ statusCode: 200, message: "ok", data: cars });
});
// car post
app.post("/api/cars", (req, res) => {
const dto = req.body;
const { error } = carCreateScheam.validate(dto);
if (error) {
return res
.status(400)
.json({ statusCode: 400, message: "Bad Request", data: error.message });
}
const newCar = {
id: cars[cars.length - 1].id + 1,
model: dto.model,
};
cars.push(newCar);
res.status(201).json({ statusCode: 201, message: "ok", data: newCar });
});
//car delete
app.delete("/api/cars/:id", (req, res) => {
let id = req.params.id;
id = Number(id);
if (isNaN(id)) {
return res.status(400).json({ statusCode: 400, message: "Invalid id" });
}
const carIndex = getById(id);
if (typeof carIndex === "undefined") {
return res.status(404).json({ statusCode: 404, message: "car not found" });
}
const deletecar = cars.splice(carIndex, 1);
res
.status(200)
.json({ statusCode: 200, message: "deleted", data: deletecar });
});
// car getById
app.get("/api/cars/:id", (req, res) => {
let id = req.params.id;
id = Number(id);
if (isNaN(id)) {
return res.status(400).json({ statusCode: 400, message: "Invalid id" });
}
const carIndex = getById(id);
if (typeof carIndex === "undefined") {
return res.status(404).json({ statusCode: 404, message: "car not found" });
}
res.status(200).json({
data: cars[carIndex],
});
});
// car patch
app.patch("/api/cars/:id", (req, res) => {
const dto = req.body;
let id = req.params.id;
id = Number(id);
if (isNaN(id)) {
return res.status(400).json({ statusCode: 400, message: "Invalid id" });
}
const carIndex = getById(id);
if (typeof carIndex === "undefined") {
return res.status(404).json({ statusCode: 404, message: "car not found" });
}
cars[carIndex].model = dto.model;
res.status(200).json({
statusCode: 200,
message: "model changed",
data: cars[carIndex].model,
});
});
// car put
app.put("/api/cars/:id", (req, res) => {
const dto = req.body;
const { error } = carCreateScheam.validate(dto);
if (error) {
return res.status(400).json({ stausCode: 400, message: error.message });
}
let id = req.params.id;
id = Number(id);
if (isNaN(id)) {
return res.status(400).json({ statusCode: 400, message: "Invalid id" });
}
const carIndex = getById(id);
if (typeof carIndex === "undefined") {
return res.status(404).json({ statusCode: 404, message: "car not found" });
}
function update() {
cars[carIndex].model = dto.model;
}
res.status(200).json({
statusCode: 200,
message: "car updated",
data: update(),
});
});
// -----------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------
// usersga tegishli metodlar
// user get
app.get("/api/users", async (req, res) => {
try {
const response = await axios.get("http://localhost:3000/api/users");
res
.status(200)
.json({ statusCode: 200, message: "ok", data: response.data });
} catch (error) {
res.status(500).json({ statusCode: 500, message: error.message });
}
});
// user post
app.post("/api/create-user", async (req, res) => {
try {
const dto = req.body;
const { error } = createUserScheam.validate(dto);π1
if (error) {
return res
.status(400)
.json({ statusCode: 400, message: "Bad Request", data: error.message });
}
const response = await axios.post("http://localhost:3000/api/users", dto);
res
.status(201)
.json({ statusCode: 201, message: "ok", data: response.data });
} catch (error) {
const statusCode = error.status || 500;
res.status(statusCode).json({
statusCode: statusCode,
message: error.response?.data?.message || error.message,
});
}
});
// user delete
app.delete("/api/user-delete/:userId", async (req, res) => {
try {
let userId = req.params.userId;
userId = Number(userId);
if (isNaN(userId)) {
return res
.status(400)
.json({ statusCode: 400, message: "Invalid userId" });
}
const deletedUser = await axios.delete(
"http://localhost:3000/api/users/" + userId
);
res
.status(200)
.json({ statusCode: 200, message: "deleted", data: deletedUser.data });
} catch (error) {
const statusCode = error.status || 500;
res.status(statusCode).json({
statusCode: statusCode,
message: error.response?.data?.message || error.message,
});
}
});
// user getById
app.get("/api/user-get/:userId", async (req, res) => {
try {
let userId = req.params.userId;
userId = Number(userId);
if (isNaN(userId)) {
return res
.status(400)
.json({ statusCode: 400, message: "Invalid userId" });
}
const getUser = await axios.get("http://localhost:3000/api/user/" + userId);
res.status(200).json({
statusCode: 200,
message: "successfully",
data: getUser.data,
});
} catch (error) {
const statusCode = error.status || 500;
res.status(statusCode).json({
statusCode: statusCode,
message: error.response?.data?.message || error.message,
});
}
});
// user patch
app.patch("/api/user-patch/:userId", async (req, res) => {
try {
let userId = req.params.userId;
userId = Number(userId);
if (isNaN(userId)) {
return res
.status(400)
.json({ statusCode: 400, message: "Invalid userId" });
}
const patchUser = await axios.patch(
"http://localhost:3000/api/user/" + userId,
req.body
);
res.status(200).json({
statusCode: 200,
message: "changed fullName",
data: patchUser.data,
});
} catch (error) {
const statusCode = error.status || 500;
res.status(statusCode).json({
statusCode: statusCode,
message: error.response?.data?.message || error.message,
});
}
});
// user put
app.put("/api/user-put/:userId", async (req, res) => {
try {
let userId = req.params.userId;
userId = Number(userId);
if (isNaN(userId)) {
return res
.status(400)
.json({ statusCode: 400, message: "Invalid userId" });
}
const putUser = await axios.put(
"http://localhost:3000/api/user/" + userId,
req.body
);
res.status(200).json({
statusCode: 200,
message: "updated",
data: putUser.data,
});
} catch (error) {
const statusCode = error.status || 500;
res.status(statusCode).json({
statusCode: statusCode,
message: error.response?.data?.message || error.message,
});
}
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
β€1π₯1π1
350 qator kod xozir + yana 180 qator bor π
π₯1π1
const express = require("express");
const cors = require("cors");
const {
userCreateSchema,
userPatchSchema,
userPutSchema,
} = require("./scheams");
const app = express();
app.use(cors());
app.use(express.json());
const users = [
{
id: 1,
login: "admin",
password: "admin",
fullName: "admin",
},
{
id: 2,
login: "admin1",
password: "admin",
fullName: "Admin Ok",
},
];
function getById(id) {
const foundUser = users.findIndex((el) => el.id === id);
if (foundUser === -1) {
return undefined;
} else {
return foundUser;
}
}
// user listni get qilish
app.get("/api/users", (req, res) => {
res.json({ stausCode: 200, message: "ok", data: users });
});
// post create qilish
app.post("/api/users", (req, res) => {
const dto = req.body;
const { error } = userCreateSchema.validate(dto);
if (error) {
return res.status(400).json({ stausCode: 400, message: error.message });
}
const newUser = {
id: users[users.length - 1].id + 1,
login: dto.login,
password: dto.password,
fullName: dto.fullName,
};
users.push(newUser);
res.status(201).json({ stausCode: 201, message: "created", data: newUser });
});
// delete berilgan id dagi ma'lumotni o'chirish
app.delete("/api/users/:id", (req, res) => {
let id = req.params.id;
id = Number(id);
if (isNaN(id)) {
return res.status(400).json({ statusCode: 400, message: "Invalid id" });
}
const userIndex = getById(id);
if (typeof userIndex === "undefined") {
return res.status(404).json({ statusCode: 404, message: "user not found" });
}
const deleteUser = users.splice(userIndex, 1);
res
.status(200)
.json({ statusCode: 200, message: "deleted", data: deleteUser });
});
// getById id berilsa o'sha id dagi ma'lumotni olib kelib berishi kerak
app.get("/api/user/:id", (req, res) => {
let id = req.params.id;
id = Number(id);
if (isNaN(id)) {
return res.status(400).json({ statusCode: 400, message: "Invalid id" });
}
const userIndex = getById(id);
if (typeof userIndex === "undefined") {
return res.status(404).json({ statusCode: 404, message: "user not found" });
}
res.status(200).json({
data: users[userIndex],
});
});
// patch metodi fullName ni o'zgartirish uchun ishlatiladi
app.patch("/api/user/:id", (req, res) => {
const dto = req.body;
const { error } = userPatchSchema.validate(dto);
if (error) {
return res.status(400).json({ stausCode: 400, message: error.message });
}
let id = req.params.id;
id = Number(id);
if (isNaN(id)) {
return res.status(400).json({ statusCode: 400, message: "Invalid id" });
}
const userIndex = getById(id);
if (typeof userIndex === "undefined") {
return res.status(404).json({ statusCode: 404, message: "user not found" });
}
users[userIndex].fullName = dto.fullName;
res.status(200).json({
statusCode: 200,
message: "fullName changed",
data: users[userIndex].fullName,
});
});
// put metodi hammasini yangilash (update qilish!)
app.put("/api/user/:id", (req, res) => {
const dto = req.body;
const { error } = userPutSchema.validate(dto);
if (error) {
return res.status(400).json({ stausCode: 400, message: error.message });
}
let id = req.params.id;
id = Number(id);
if (isNaN(id)) {
return res.status(400).json({ statusCode: 400, message: "Invalid id" });
}
const userIndex = getById(id);
if (typeof userIndex === "undefined") {
return res.status(404).json({ statusCode: 404, message: "user not found" });
}
function update() {
users[userIndex].fullName = dto.fullName;
users[userIndex].password = dto.password;
users[userIndex].login = dto.login;
}
res.status(200).json({
statusCode: 200,
message: "user updated",
data: update(),
});
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});mayda fayllar qo'shilganda 600 qator kod bo'larkan π ( sabr bersinπ)
π₯3π1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CHAT</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f9f9f9;
}
#messageDisplay {
width: 100%;
max-width: 500px;
margin-bottom: 20px;
padding: 10px;
background: #00eeff;
border: 1px solid #f60808;
border-radius: 5px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
overflow-y: auto;
max-height: 300px;
}
input {
width: 100%;
max-width: 492px;
height: 40px;
margin-bottom: 10px;
font-size: 16px;
border-radius: 5px;
background-color: rgb(255, 255, 255);
}
button {
text-align: center;
padding: 10px 20px;
font-size: 16px;
color: white;
background-color: #0ab919;
border: none;
border-radius: 5px;
cursor: pointer;
margin-bottom: 10px;
margin-left: 210px;
}
button:hover {
background-color: #185fab;
}
input {
font-size: 40px;
}
p {
text-align: center;
font-size: 20px;
font-style: italic;
border-radius: 10px;
margin-right: 120px;
margin-left: 80px;
margin-bottom: 10px;
padding: 0;
color: white;
background-color: rgb(31, 100, 149);
}
input::placeholder {
font-style: italic;
font-size: 40px;
}
li {
margin: 0px;
font-size: 30px;
background-color: rgb(251, 251, 243);
font-style: italic;
}
select {
margin-left: 100px;
color: rgb(21, 83, 119);
background-color: rgb(67, 238, 15);
border-radius: 5px;
}
</style>
</head>
<body>
<div id="messageDisplay">
<ul id="messages">
<select id="select"></select>
<p>THIS IS MY STILEπΏ</p>
</ul>
<input
id="messageInput"
autocomplete="on"
placeholder="Type your message..."
/>
<button id="sendButton">SEND</button>
</div>
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script src="./main.js"></script>
</body>
</html>
π₯3π1
const socket = io("http://localhost:7777");
const messageDisplay = document.getElementById("messages");
const sendButton = document.getElementById("sendButton");
const messageInput = document.getElementById("messageInput");
const select = document.getElementById("select");
socket.on("onlineUsers", ({ data }) => {
select.innerHTML = "";
data.forEach((onlineUser, index) => {
const option = document.createElement("option");
option.value = onlineUser;
option.textContent = index + 1 + " ) " + onlineUser;
select.appendChild(option);
});
});
socket.on("message", ({ data }) => {
const p = document.createElement("p");
p.textContent = data.message;
messageDisplay.appendChild(p);
});
sendButton.addEventListener("click", () => {
const message = messageInput.value.trim();
if (message) {
socket.emit("send", { message });
messageInput.value = "";
}
});π₯2π2π₯°1
const { v4: uuidv4 } = require("uuid");
const express = require("express");
const cors = require("cors");
const http = require("http");
const socketIo = require("socket.io");
const app = express();
const server = http.createServer(app);
const io = socketIo(server, { cors: { origin: "*" } });
class ResData {
constructor(statusCode, message, data) {
this.statusCode = statusCode;
this.message = message;
this.data = data;
}
}
app.use(cors());
app.use(express.json());
const messages = [];
const onlineUsers = new Set();
io.on("connection", (socket) => {
console.log("user is connected:", socket.id);
onlineUsers.add(socket.id);
io.emit(
"onlineUsers",
new ResData(200, "online users updated", Array.from(onlineUsers))
);
socket.on("send", (data) => {
if (!data.message) {
return socket.emit("error", new ResData(400, "message is not defined"));
}
const newMessage = {
id: uuidv4(),
senderId: socket.id,
message: data.message,
};
messages.push(newMessage);
socket.broadcast.emit(
"message",
new ResData(200, "new message received", newMessage)
);
});
socket.on("disconnect", () => {
console.log("user is disconnected:", socket.id);
onlineUsers.delete(socket.id);
io.emit(
"onlineUsers",
new ResData(200, "online users updated", Array.from(onlineUsers))
);
});
});
// get metodi
app.get("/messages", (req, res) => {
res.json(new ResData(200, "All messages", messages));
});
// post metodi
app.post("/messages", (req, res) => {
const { message } = req.body;
if (!message) {
return res.status(400).json(new ResData(400, "must be a message"));
}
const newMessage = {
id: uuidv4(),
senderId: "server",
message,
};
messages.push(newMessage);
io.emit("message", new ResData(200, "new message added", newMessage));
res
.status(201)
.json(new ResData(201, "message created successfully", newMessage));
});
// put metodi
app.put("/messages/:id", (req, res) => {
const { id } = req.params;
const { message } = req.body;
const index = messages.findIndex((msg) => msg.id === id);
if (index === -1) {
return res.status(404).json(new ResData(404, "message is not defined"));
}
messages[index].message = message;
io.emit(
"messageUpdated",
new ResData(200, "message updated", messages[index])
);
res.json(new ResData(200, "message updated successfully", messages[index]));
});
// delete metodi
app.delete("/messages/:id", (req, res) => {
const { id } = req.params;
const index = messages.findIndex((msg) => msg.id === id);
if (index === -1) {
return res.status(404).json(new ResData(404, "message is not defined"));
}
const deletedMessage = messages.splice(index, 1);
io.emit(
"messageDeleted",
new ResData(200, "message deleted", deletedMessage[0])
);
res.json(new ResData(200, "message deleted successfully", deletedMessage[0]));
});
server.listen(7777, () => {
console.log("http://localhost:7777");
});π₯7π1
-- Darsdagilar
create DATABASE ok;
--
create SCHEMA ok;
--
create TABLE users(
id serial primary key,
email varchar(255) not null unique,
password varchar(255) not null
);
--
create TABLE ok.users(
id serial primary key,
name varchar(255) not null,
email varchar(255) not null unique,
password varchar(255) not null
);
--
--
insert into users(email, password)
values ('no@gmail.com', 'test'),
('no2@gmail.com', 'test'),
('no3@gmail.com', 'test'),
('no4@gmail.com', 'test'),
('no5@gmail.com', 'test'),
('no6@gmail.com', 'test'),
('no7@gmail.com', 'test'),
('no8@gmail.com', 'test');
SELECT * FROM users;
--
insert into ok.users(email, password, birthday, is_marrige)
values ('no9@gmail.com', 'test', '2001-07-05', false),
('no@gmail.com', 'test', '2001-07-06', false),
('no2@gmail.com', 'test', '2001-07-07', true),
('no3@gmail.com', 'test', '2001-07-08', false),
('no4@gmail.com', 'test', '2001-07-09', true),
('no5@gmail.com', 'test', '2001-07-10', false),
('no6@gmail.com', 'test', '2001-07-11', true),
('no7@gmail.com', 'test', '2001-07-12', false),
('no8@gmail.com', 'test', '2001-07-02', true);
SELECT * FROM ok.users;
--
update ok.users set password='ok' where is_marrige=true;
--
select * from ok.users where full_name like '%n';
select * from ok.users where full_name ilike 'h%';
-- Uyga vazifa
create DATABASE hw1; -- database homework 6month 1 lesson
--
create SCHEMA schema_1;
--USERS
create table schema_1.users(
id serial primary key,
full_name varchar(64) default null,
email varchar(64) unique not null,
password text not null,
role varchar(64) default null );
--
--
insert into schema_1.users(full_name, email, password, role)
values ('Ziyodullo Najmiddinov', 'ziyodillo@gmail.com', '1234', 'admin'),
('Muhammadali Abdurasulov', 'ali@gmail.com', '1234', 'manager'),
('Ergashev Vasliddin', 'vasliddin@gmail.com', '2007', 'admin'),
('Abdurahmonov Ziyodullo', 'ziyodullo012@gmail.com', '1223', 'admin'),
('user1', 'user@gmail.com', '1223', 'manager');
SELECT * FROM schema_1.users;
where full_name between 'Ziyodullo Najmiddinov' and 'Abdurahmonov Ziyodullo'
update schema_1.users set role='leader' where email='user@gmail.com';
DELETE FROM schema_1.users WHERE role = 'leader';
select * from ok.users where full_name like '%Z';
select * from ok.users where full_name ilike '%N';
--
--
--TASKS
CREATE TABLE schema_1.tasks (
id SERIAL PRIMARY KEY,
title VARCHAR(64) DEFAULT NULL,
description VARCHAR(64) DEFAULT NULL,
start_date TIMESTAMP DEFAULT NOW(),
end_date TIMESTAMP DEFAULT NOW(),
status TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
--
--
insert into schema_1.tasks(title, status,description)
values ('tayyor', 'created', 'new1'),
('tayyor2', 'created', 'new2'),
('tayyor3', 'created', 'new3'),
('tayyor4', 'created', 'new4');
SELECT * FROM schema_1.tasks;
where description between 'new1' and 'new4'
update schema_1.tasks set title='ok' where status='created';
DELETE FROM schema_1.tasks WHERE description = 'new1';
select * from schema_1.tasks where description like '%n';
select * from schema_1.tasks where description ilike '%3';
--
--
--NOTIFICATIONS
create table schema_1.notifications(
id serial primary key,
title varchar(64) default null,
message varchar(64) not null,
is_global boolean not null);
--
--
insert into schema_1.notifications(title, message,is_global)
values ('new', 'created', true),
('new2', 'ended', false),
('new3', 'inprogress', true),
('new4', 'created', false);
SELECT * FROM schema_1.notifications;
where title between 'ok' and 'ok';
update schema_1.tasks set title='ok' where message='created';
DELETE FROM schema_1.tasks WHERE title = 'new';
select * from schema_1.tasks where title like '%n';
select * from schema_1.tasks where title ilike '%4';
--
--
--MESSAGES
create table schema_1.messages(
id serial primary key,
message varchar(64) not null,
from_ varchar(64) default null,
to_ varchar(64) default null,
is_read boolean not null
);
π₯2β€1π€1π1
--
--
insert into schema_1.messages(message, from_, to_, is_read)
values ('salom', 'you', 'I', true),
('salom2', 'user1', 'you', false),
('salom3', 'user2', 'I', true),
('salom4', 'you', 'he', false);
SELECT * FROM schema_1.messages;
where message between 'salom' and 'salom4';
update schema_1.messages set from_='I' where is_read=true;
DELETE FROM schema_1.messages where to_ = 'you';
select * from schema_1.messages where message like 's%';
select * from schema_1.messages where message ilike '%4';
--
π₯3π€2π1π¦1
create schema hw4;
create table hw4.cars (
id serial primary key,
model varchar(255) not null,
price int not null,
count int default 0
);
--
--
insert into hw4.cars(model,price,count) values
('BMW',10000,50),
('ROLLS ROYCE',20000,10),
('TOYOTA',8000,1000),
('MERCEDEZ',1000,40),
('SUPRA',12000,15);
select * from hw4.cars;
--user create
create table hw4.users(
id serial primary key,
fullname varchar(255),
balance int not null
);
insert into hw4.users(fullname,balance) values
('user1',100000),
('user2',200000),
('user3',80000),
('user4',10000),
('user5',120000);
-- first function...
create or replace function get_price_car(min_price int)
returns table(id int, model varchar(255), price int, count int)
language plpgsql
as
$$
begin
return query
select
c.id,
c.model,
c.price,
c.count from hw4.cars as c
where c.price > min_price order by price ASC;
end;
$$;
select * from get_price_car(8000);
-- second function...
create or replace function get_car_id(car_id int)
returns text
language plpgsql
as
$$
declare car_list text;
begin
select concat(
'id: ', c.id,
', model: ', c.model,
', price: ', c.price,
'. count: ', c.count)
into car_list
from hw4.cars as c
where c.id = car_id;
return car_list;
end;
$$;
select * from get_car_id(1);
--procedure
create or replace procedure buy_car(car_id int, car_count int, user_id int)
language plpgsql
as
$$
declare
car_price int;
car_count_available int;
user_balance int;
begin
select price, count into car_price, car_count_available
from hw4.cars
where id = car_id;
if car_price is null or car_count_available is null then
raise notice 'mashina topilmadi';
rollback;
return;
end if;
select balance into user_balance
from hw4.users
where id = user_id;
if user_balance is null then
raise notice 'foydalanuvchi topilmadi';
rollback;
return;
end if;
if user_balance < car_count * car_price then
raise notice 'foydalanuvchining balansida yetarli pul topilmadi';
rollback;
return;
end if;
if car_count_available < car_count then
raise notice 'mashinadan buncha emas';
rollback;
return;
end if;
update hw4.cars
set count = count - car_count
where id = car_id;
update hw4.users
set balance = balance - car_count * car_price
where id = user_id;
select balance into user_balance
from hw4.users
where id = user_id;
if user_balance < 5 then
raise notice 'foydalanuvchining balansida minimal summa 5 som dan kam';
rollback;
return;
end if;
commit;
raise notice 'buyurtma muvaffaqiyatli amalga oshirildi. % ta mashina sotib olindi', car_count;
end;
$$;
call buy_car(1,2,1);
π₯6π2π1π1π1π1
Kodingda try bor-u, lekin hayotingda catch ishlamayapti. Xatolarni toβgβrilash oβrniga, ularni "feature" deb nomlab qoβyayotgan backendchisan. Katta loyihalar qilishni orzu qilasan, lekin hozircha faqat res.send("Hello World") bilan yuribsan.
Sen oβzingni zoβr deb bilasan, lekin MongoDB'dagi dokumentlar sendan mustahkamroq qaror qabul qiladi. Frontendni yomon koβrasan, chunki sen qilgan API-larga hech kim request yubormaydi. Aslida esa backendchilar ham frontendchilar kabi "loading..." holatida yashaydi.
Xoβjayin, sen senior boβlishni orzu qilasan, lekin GitHub commitlaring "Initial commit" bilan tugagan. Agar sening dasturlash yoβlingni "ping" qilib tekshirsak, request timeout berib ketadi.
Lekin sendan yaxshi backendchi chiqadi!"π€£2π€·ββ1π1π₯1π1π1