Skip to content

Commit

Permalink
insert and update -works
Browse files Browse the repository at this point in the history
  • Loading branch information
YoavKo committed May 1, 2022
1 parent f4c09c7 commit 26f49b8
Show file tree
Hide file tree
Showing 5 changed files with 119 additions and 74 deletions.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,37 @@ DB modoal:
| weapon | varchar(255) | YES | | NULL | |
| vehicle | varchar(255) | YES | | NULL | |
* For getAllien(id) At first I considered turning in three queries to the database, the first to
get the data about the alien himself, the second to get his commander's name and the third to
get the personal numbers of his supervisors, like:
```SQL
SELECT * FROM aliens WHERE id = <id>;
SELECT id FROM aliens WHERE commander_id = <id>;
SELECT name FROM aliens WHERE id = <commander_id>;
```
Then I realized that I could with a more complex query get all the data in one request to the DB.
```SQL
SELECT
A.*,
B.name AS commander_name,
GROUP_CONCAT(C.id) AS supevised_ids
FROM
aliens A
LEFT JOIN aliens B ON A.commander_id = B.id
LEFT JOIN aliens C ON A.id = C.commander_id
WHERE
A.id = <id>;
```
Empty values are automatically revalued to NULL.
for example where <id> in (4, 7):
| id | commander_id | name | type | weapon | vehicle | commander_name | supevised_ids |
|----|--------------|------------------|------------------------|--------|--------------|----------------|---------------|
| 4 | 6 | Malcom Soval | alien-commanders | NULL | Bird scooter | Rinya Galen | 1,2 |
| 7 | NULL | Frida Trualyksoe | alien-chief-commanders | NULL | Egged Bus | NULL | NULL |
155 changes: 83 additions & 72 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,113 +1,124 @@
const Koa = require('koa');
const Router = require('@koa/router');
const bodyParser = require('koa-bodyparser');
mysql = require('mysql2');

const mysql = require('mysql2');
const bluebird = require('bluebird');

// midelwear - setup;
const app = new Koa();
const router = new Router();
const db = mysql.createConnection({
user: 'root',
password: 'example',
database: 'aliensdb'
user: 'root',
password: 'example',
database: 'aliensdb'
});


app.use(bodyParser());

const querysTamlates = {
getAll: "SELECT * FROM aliens",
getId: "SELECT * FROM aliens WHERE id = ?",
getSupervisedAliensIds: "SELECT id FROM aliens WHERE commander_id = ?",
getNameById: "SELECT name FROM aliens WHERE id = ?"
getAll: ` SELECT A.id, A.name, A.weapon, A.commander_id, B.name AS commander_name
FROM aliens A LEFT JOIN aliens B ON A.commander_id = B.id
GROUP BY A.id; `,

getId: `SELECT A.id, A.name, A.weapon, A.commander_id, B.name AS commander_name,
GROUP_CONCAT(C.id) AS supevised_ids
FROM aliens A LEFT JOIN aliens B ON A.commander_id = B.id
LEFT JOIN aliens C ON A.id = C.commander_id
WHERE A.id = ?;`,

updateId: `UPDATE aliens SET name = ?, weapon = ?, vehicle = ? WHERE id = ?`,

insert: `INSERT INTO aliens(commander_id, name, weapon, vehicle, type)
VALUES (?, ?, ?, ?, ?)`
};


// utils funcs
const buildIdNameDict = (allAliens) => {
const res = {};
allAliens.forEach(alian => { res[alian.id] = alian.name });
return res;
};

const getSupervisedAliensIdsFromDB = (id) => {
let ids = [];
db.query(querysTamlates.getSupervisedAliensIds, [id], (err, results) =>{
results.forEach(res => ids.push(res.id));
});
return ids;
console.log(ids);
};


const getCommanderMameFromDB = async function(commander_id){
let commander_name = "";
let q = await db.query(querysTamlates.getNameById, [commander_id]);
console.log("@@@@ ", q);
q.then(res => commander_name = res);
return commander_name;
/*
, (err, res) => {
console.log('res-1', res[0].name);
commander_name = res[0].name;
return commander_name;
}); */
// input validation:
const validateInsert = function(values){
//TODO impl
// is commander_id exist in db and by the commaner's type if cane manege
// 1 more and if the type of the new alien is one rank below the commander's type.
// - can be done with 1 sql req of bool calcolation.
//
// is the weapon or vehicle are aloowed to it's type.
// - can be check only use <values>.-
return true;
};

// input validation:
const validateUpdate = function(values){
//TODO impl
// is the weapon or vehicle are aloowed to it's type.
// - can be done with 1 sql req or get the alien's type, and then lockaly..
return true;
};


// API funcs:
const getAll = function(ctx){
db.query(querysTamlates.getAll, (err, allAliens) => {
//console.log(results);
const id_name_dict = buildIdNameDict(allAliens);

allAliens.forEach(alien => {
alien.commander_name = id_name_dict[alien.commander_id];
delete alien.type;
delete alien.vehicle;
db.promise().query(querysTamlates.getAll)
.then((res) => {
ctx.response.body = res[0];
ctx.set('content-type', 'application/json');
ctx.status = 200;
console.log(ctx.response);
});

ctx.body = allAliens;
//ctx.type = "application/json";
//ctx.status = 200;
});
};

const getAlien = function(ctx){
const id = ctx.params.id;
db.query(querysTamlates.getId, [id], (err, alien) => {
//console.log(results);
alien = alien[0];
// alien.commander_name = getCommanderMameFromDB(alien.commander_id);
// alien.supervised_aliens_ids = getSupervisedAliensIdsFromDB(alien.id);
delete alien.type;
delete alien.vehicle;

db.promise().query(querysTamlates.getId, [id])
.then((res) => {
alien = res[0][0];
ctx.body = alien;

//console.log(ctx.response);
console.log(ctx.response);
});



};

const updateAlien = function(ctx){
ctx.body = `updateAlien ${ctx.params.id} data[${JSON.stringify(ctx.request.body)}]\n`
/*
console.log(ctx.request);
ctx.response.body = ctx.request.body;
ctx.response.body.method = ctx.request.method;
console.log(ctx.response)
*/
const reqData = ctx.request.body;

const id = ctx.params.id;
const name = reqData.name;
const weapon = reqData.weapon;
const vehicle = reqData.vehicle;
const valuseArray = [name, weapon, vehicle, id];

if(validateUpdate(valuseArray)) {
db.promise().query(querysTamlates.updateId, valuseArray)
.then((res) => {
console.log(res);
ctx.status = 204;
console.log(ctx.response);
});
} else {
//TODO handle bad reqwest.
}
};


const newAlien = function(ctx){
ctx.body = `newAlien data[${JSON.stringify(ctx.request.body)}]\n`

const reqData = ctx.request.body;

const commander_id = reqData.commander_id;
const name = reqData.name;
const weapon = reqData.weapon;
const vehicle = reqData.vehicle;
const type = reqData.type;
const valuseArray = [commander_id, name, weapon, vehicle, type];

if(validateInsert(valuseArray)) {
db.promise().query(querysTamlates.insert, valuseArray)
.then((res) => {
console.log(res);
ctx.status = 201;
console.log(ctx.response);
});
} else {
//TODO handle bad reqwest.
}
};


Expand Down
2 changes: 1 addition & 1 deletion db_data_init.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const db = mysql.createConnection({

db.query('DELETE FROM aliens;');

const strOrNULL = (str) => { return str ? `${str}` : null; };
const strOrNULL = (str) => { return str ? str : null; };

const insertQuery = `INSERT INTO aliens(id, commander_id, name, weapon, vehicle, type)
VALUES ( ?, ?, ?, ?, ?, ?)`;
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ services:
expose:
- 3306
environment:
MYSQL_ROOT_PASSWORD: Aa123456
MYSQL_ROOT_PASSWORD: example

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"main": "api.js",
"dependencies": {
"@koa/router": "^10.1.1",
"bluebird": "^3.7.2",
"koa": "^2.13.4",
"koa-bodyparser": "^4.3.0",
"koa-router": "^10.1.1",
Expand Down

0 comments on commit 26f49b8

Please sign in to comment.