Skip to content

Commit 8c6cf07

Browse files
author
Pankaj Patel
committed
crud helpers
1 parent 8043d10 commit 8c6cf07

File tree

11 files changed

+245
-78
lines changed

11 files changed

+245
-78
lines changed

.env.example

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
DB_HOST=localhost
2+
DB_USER=root
3+
DB_PASS=
4+
DB_DATABASE=twitter_clone

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,4 @@ typings/
6161
.next
6262

6363
*.spf
64+
.env

README.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,71 @@ You cna run this collection in Postman with following button:
1717

1818

1919
Or Download and import in Postman from here: <a href="./Twitter Clone.postman_collection.json" download>Download</a>
20+
21+
-----
22+
23+
```sql
24+
CREATE DATABASE twitter_clone;
25+
26+
use twitter_clone;
27+
28+
CREATE TABLE users(
29+
id int NOT NULL AUTO_INCREMENT,
30+
username varchar(15) NOT NULL,
31+
password varchar(32) NOT NULL,
32+
followers int DEFAULT 0,
33+
following int DEFAULT 0,
34+
tweets int DEFAULT 0,
35+
PRIMARY KEY (id)
36+
);
37+
38+
CREATE TABLE following(
39+
id int NOT NULL AUTO_INCREMENT,
40+
user1_id int REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
41+
user2_id int REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
42+
PRIMARY KEY (id)
43+
);
44+
45+
CREATE TABLE tweets(
46+
id int NOT NULL AUTO_INCREMENT,
47+
username varchar(15) NOT NULL,
48+
user_id int REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
49+
tweet varchar(140) NOT NULL,
50+
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
51+
PRIMARY KEY (id)
52+
);
53+
54+
INSERT INTO USERS(username, password) VALUE('pankaj', MD5('pankaj'));
55+
56+
INSERT INTO USERS(username, password) VALUE('tim', MD5('tim'));
57+
58+
INSERT INTO USERS(username, password) VALUE('jim', MD5('jim'));
59+
60+
INSERT INTO TWEETS(username, user_id, tweet) VALUE('pankaj', 1, 'Hello World Again!');
61+
62+
INSERT INTO FOLLOWING(user1_id, user2_id) VALUE(1, 2);
63+
INSERT INTO FOLLOWING(user1_id, user2_id) VALUE(1, 3);
64+
INSERT INTO FOLLOWING(user1_id, user2_id) VALUE(3, 1);
65+
66+
SELECT * FROM tweets;
67+
68+
# Followers
69+
70+
SELECT
71+
USER_INFO.*, username as user1_username
72+
FROM (SELECT
73+
user1_id, user2_id, username as user2_username
74+
FROM FOLLOWING LEFT JOIN USERS ON user2_id = users.id
75+
WHERE user1_id = 1) as USER_INFO
76+
LEFT JOIN USERS ON user1_id = users.id ;
77+
78+
# Following
79+
80+
SELECT
81+
USER_INFO.*, username as user1_username
82+
FROM (SELECT
83+
user1_id, user2_id, username as user2_username
84+
FROM FOLLOWING LEFT JOIN USERS ON user2_id = users.id
85+
WHERE user2_id = 1) as USER_INFO
86+
LEFT JOIN USERS ON user1_id = users.id ;
87+
```

Twitter Clone.postman_collection.json

Lines changed: 38 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"info": {
33
"_postman_id": "78149020-40a3-4657-80a9-7683bdae2c78",
44
"name": "Twitter Clone",
5-
"description": "This collection is created to help understand the Rest API creation on Node.js with Express and MySQL\n\nThe original article can be found here: https://time2hack.com/2019/09/creating-rest-api-in-node-js-with-express-and-mysql",
5+
"description": "This collection is created to help understand the Rest API creation on Node.js with Express and MySQL\n\nThe original article can be found here: https://time2hack.com/2019/09/creating-rest-api-in-node-js-with-express-and-mysql/",
66
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
77
},
88
"item": [
@@ -223,12 +223,12 @@
223223
"urlencoded": [
224224
{
225225
"key": "username",
226-
"value": "jim",
226+
"value": "r_{{$randomUserName}}",
227227
"type": "text"
228228
},
229229
{
230230
"key": "password",
231-
"value": "jim",
231+
"value": "random-password",
232232
"type": "text"
233233
}
234234
]
@@ -241,18 +241,6 @@
241241
"path": [
242242
"auth",
243243
"register"
244-
],
245-
"query": [
246-
{
247-
"key": "username",
248-
"value": "",
249-
"disabled": true
250-
},
251-
{
252-
"key": "password",
253-
"value": "",
254-
"disabled": true
255-
}
256244
]
257245
},
258246
"description": "# Register New User\n---\n\n## Params\n\n`username`: `String`\n`password`: `String`\n\nReturns the new User's ID and Set's to Environment"
@@ -319,12 +307,46 @@
319307
"response": []
320308
}
321309
],
310+
"event": [
311+
{
312+
"listen": "prerequest",
313+
"script": {
314+
"id": "9f38fe7c-852d-47ea-94c0-a30a02fe80f1",
315+
"type": "text/javascript",
316+
"exec": [
317+
""
318+
]
319+
}
320+
},
321+
{
322+
"listen": "test",
323+
"script": {
324+
"id": "fbd831b3-89ea-4af7-9e1c-b34bd57dba5e",
325+
"type": "text/javascript",
326+
"exec": [
327+
""
328+
]
329+
}
330+
}
331+
],
322332
"variable": [
323333
{
324-
"id": "363978da-cd5b-42e5-97e7-a8f9aab3fbd0",
334+
"id": "163f6187-2a19-4028-b6d8-ec8709bc560b",
335+
"key": "url",
336+
"value": "http://localhost:3000",
337+
"type": "string"
338+
},
339+
{
340+
"id": "974aa83a-3a22-483b-8363-e514a2742d5e",
325341
"key": "user",
326342
"value": "1",
327343
"type": "string"
344+
},
345+
{
346+
"id": "ddcb6d1f-4270-4364-bdcf-5e75ec9afeb4",
347+
"key": "randomPassword",
348+
"value": "random-password",
349+
"type": "string"
328350
}
329351
],
330352
"protocolProfileBehavior": {}

app-middlewares/auth.js

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,23 @@ const query = require('../helpers/query');
55
const router = express.Router();
66
const dbConfig = require('../dbConfig');
77

8+
const create = require('../crud/create');
9+
810
router.post('/register', async (req, res) => {
911
const { username, password } = req.body;
1012
const conn = await connection(dbConfig).catch(e => {});
11-
const user = await query(
13+
const result = await create(
1214
conn,
13-
`INSERT INTO USERS(username, password) VALUE(?, MD5(?));`,
14-
[username, password]
15+
'USERS',
16+
['username', 'password'],
17+
[username, { toString: () => `MD5('${password}')`}]
1518
);
16-
if (user.insertId) {
17-
res.send(await query(conn, `SELECT id, username FROM USERS WHERE ID=?`, [user.insertId]))
18-
return;
19-
}
20-
res.send({ id: null, username: null });
19+
20+
const [user = {}] = result;
21+
res.send({
22+
id: user.id || null,
23+
username: user.username || null,
24+
});
2125
});
2226

2327
router.post('/login', async (req, res) => {

crud/create.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
const query = require('../helpers/query');
2+
const valuesForQuery = require('../helpers/values-for-insert');
3+
4+
/**
5+
* @param {} conn MySQL Connection reference
6+
* @param {String} table Table to insert the values
7+
* @param {[String]} columns Array of column names
8+
* @param {[String]} values Array of values for those column names, can be multidientional
9+
*/
10+
module.exports = async (conn, table, columns, values) => {
11+
const VALUES = valuesForQuery(values)
12+
try {
13+
const user = await query(conn, `INSERT INTO ${table}(${columns.join(', ')}) VALUES ${VALUES};`);
14+
if (user.insertId) {
15+
console.log(user.insertId);
16+
return await query(conn, `SELECT * FROM ${table} WHERE ID=?`, [user.insertId]);
17+
}
18+
return user;
19+
} catch(e) { console.log(e)}
20+
}

dbConfig.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
const dotenv = require("dotenv")
2+
3+
dotenv.config();
4+
15
// Get the Host from Environment or use default
26
const host = process.env.DB_HOST || 'localhost';
37

helpers/query.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ module.exports = async (conn, q, params) => new Promise(
88
resolve(result);
99
}
1010
conn.query(q, params, handler);
11-
});
11+
}).catch(console.log);

helpers/values-for-insert.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {[String]} values Array of values for those column names
3+
*/
4+
const valueForQuery = (_values) => {
5+
const values = _values.map(item => {
6+
let val;
7+
switch (typeof item) {
8+
case 'number':
9+
return item;
10+
case 'string':
11+
val = item;
12+
break;
13+
default:
14+
return item.toString();
15+
}
16+
return `'${val}'`;
17+
})
18+
return `(${values.join(', ')})`;
19+
};
20+
21+
/**
22+
* @param {[String]} values Array of values for those column names, can be multidientional
23+
*/
24+
const valuesForQuery = (values) => {
25+
const value = values[0];
26+
let VALUES = '';
27+
if (value instanceof Array) {
28+
VALUES = values.map(valueForQuery).join(', ')
29+
} else {
30+
VALUES = valueForQuery(values);
31+
}
32+
return VALUES;
33+
}
34+
35+
module.exports = {
36+
valueForQuery,
37+
valuesForQuery,
38+
}

0 commit comments

Comments
 (0)