Skip to content
This repository was archived by the owner on Apr 19, 2023. It is now read-only.

Commit 2bb3045

Browse files
✨ Add register
1 parent d915e9f commit 2bb3045

File tree

9 files changed

+118
-15
lines changed

9 files changed

+118
-15
lines changed

package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"watch-server": "nodemon dist/index.js"
1414
},
1515
"devDependencies": {
16+
"@types/bcrypt": "^3.0.0",
1617
"@types/dotenv": "^6.1.1",
1718
"@types/express": "^4.16.1",
1819
"@types/jest": "^24.0.11",
@@ -30,6 +31,7 @@
3031
"typescript": "^3.4.4"
3132
},
3233
"dependencies": {
34+
"bcrypt": "^3.0.6",
3335
"mysql": "^2.17.1",
3436
"reflect-metadata": "^0.1.13"
3537
}

src/crud/user.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { query, tableValues } from "../helpers/mysql";
2+
import { User } from "../interfaces/tables/user";
3+
import { capitalizeFirstAndLastLetter } from "../helpers/string";
4+
import { hash } from "bcrypt";
5+
6+
export const listAllUsers = async () => {
7+
return <User[]>await query("SELECT * from users");
8+
};
9+
10+
export const createUser = async (user: User) => {
11+
// Clean up values
12+
user.name = capitalizeFirstAndLastLetter(user.name);
13+
// Default values for user
14+
user.nickname = user.nickname || user.name.split(" ")[0];
15+
user.twoFactorEnabled = user.twoFactorEnabled || false;
16+
user.timezone = user.timezone || "Europe/Amsterdam";
17+
user.password = await hash(user.password || "", 8);
18+
user.notificationEmails = user.notificationEmails || 1;
19+
user.preferredLanguage = user.preferredLanguage || "en-us";
20+
user.prefersReducedMotion = user.prefersReducedMotion || false;
21+
user.createdAt = new Date();
22+
user.updatedAt = user.createdAt;
23+
// Create user
24+
return await query(
25+
`INSERT INTO users ${tableValues(user)}`,
26+
Object.values(user)
27+
);
28+
};

src/helpers/crud.ts

Lines changed: 0 additions & 6 deletions
This file was deleted.

src/helpers/mysql.ts

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
1-
import { createPool, PoolConnection } from "mysql";
1+
import { createPool } from "mysql";
22
import {
33
DB_HOST,
44
DB_USERNAME,
55
DB_PORT,
66
DB_PASSWORD,
77
DB_DATABASE
88
} from "../config";
9+
import { User } from "../interfaces/tables/user";
10+
import { BackupCode } from "../interfaces/tables/backup-codes";
11+
import { Email } from "../interfaces/tables/emails";
12+
import { Membership } from "../interfaces/tables/memberships";
13+
import { Organization } from "../interfaces/tables/organization";
914

1015
export const pool = createPool({
1116
host: DB_HOST,
@@ -17,15 +22,43 @@ export const pool = createPool({
1722

1823
export const query = (
1924
queryString: string,
20-
values?: (string | number | boolean | Date)[]
25+
values?: (string | number | boolean | Date | undefined)[]
2126
) =>
2227
new Promise((resolve, reject) => {
2328
pool.getConnection((error, connection) => {
2429
if (error) return reject(error);
30+
if (values) values = cleanValues(values);
2531
connection.query(queryString, values, (error, result) => {
2632
connection.destroy();
2733
if (error) return reject(error);
2834
resolve(result);
2935
});
3036
});
3137
});
38+
39+
export const tableValues = (
40+
object: User | BackupCode | Email | Membership | Organization
41+
) => {
42+
const values = Object.keys(object)
43+
.map(() => "?")
44+
.join(", ");
45+
const query = `(${Object.keys(object).join(", ")}) VALUES (${values})`;
46+
return query;
47+
};
48+
49+
export const cleanValues = (
50+
values: (string | number | boolean | Date | undefined)[]
51+
) => {
52+
values = values.map(value => {
53+
// Convert true to 1, false to 0
54+
if (typeof value === "boolean") value = !!value;
55+
// Convert Date to mysql datetime
56+
if (typeof value === "object" && typeof value.getMonth === "function")
57+
value = value
58+
.toISOString()
59+
.slice(0, 19)
60+
.replace("T", " ");
61+
return value;
62+
});
63+
return values;
64+
};

src/helpers/string.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
export const capitalizeEachFirstLetter = (string: string) =>
2+
(string = string
3+
.toLowerCase()
4+
.split(" ")
5+
.map(s => s.charAt(0).toUpperCase() + s.toLowerCase().substring(1))
6+
.join(" "));
7+
8+
export const capitalizeFirstAndLastLetter = (string: string) => {
9+
const words = string.split(" ");
10+
words[0] = capitalizeFirstLetter(words[0]);
11+
words[words.length - 1] = capitalizeFirstLetter(words[words.length - 1]);
12+
return words.join(" ");
13+
};
14+
15+
export const capitalizeFirstLetter = (string: string) =>
16+
string.charAt(0).toUpperCase() + string.toLowerCase().slice(1);

src/index.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
import express from "express";
22
import { PORT } from "./config";
3-
import { listAllUsers } from "./helpers/crud";
3+
import { register } from "./rest/auth";
44

55
const app = express();
66

77
app.get("/", (req, res) => res.json({ hello: "world" }));
88
app.get("/create-account", async (req, res) => {
99
try {
10-
const users = await listAllUsers();
10+
const users = await register(
11+
{ name: "Anand Chowdhary" },
12+
"anandchowdhary@gmail.com"
13+
);
1114
res.json({ success: true, users });
1215
} catch (error) {
1316
console.log("Error", error);

src/interfaces/tables/user.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
export interface User {
2-
id: number;
2+
id?: number;
33
name: string;
4-
nickname: string;
4+
nickname?: string;
55
primaryEmail?: number;
6-
password: string;
6+
password?: string;
77
twoFactorEnabled?: boolean;
88
twoFactorSecret?: string;
99
countryCode?: string;

src/rest/auth.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { User } from "../interfaces/tables/user";
2+
import { createUser } from "../crud/user";
3+
4+
export const register = async (
5+
user?: User,
6+
email?: string,
7+
organizationId?: string
8+
) => {
9+
const result = await createUser({
10+
name: "Anand Chowdhary"
11+
});
12+
console.log(result);
13+
return "done!";
14+
};

yarn.lock

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,11 @@
321321
dependencies:
322322
"@babel/types" "^7.3.0"
323323

324+
"@types/bcrypt@^3.0.0":
325+
version "3.0.0"
326+
resolved "https://registry.yarnpkg.com/@types/bcrypt/-/bcrypt-3.0.0.tgz#851489a9065a067cb7f3c9cbe4ce9bed8bba0876"
327+
integrity sha512-nohgNyv+1ViVcubKBh0+XiNJ3dO8nYu///9aJ4cgSqv70gBL+94SNy/iC2NLzKPT2Zt/QavrOkBVbZRLZmw6NQ==
328+
324329
"@types/body-parser@*":
325330
version "1.17.0"
326331
resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.17.0.tgz#9f5c9d9bd04bb54be32d5eb9fc0d8c974e6cf58c"
@@ -693,6 +698,14 @@ bcrypt-pbkdf@^1.0.0:
693698
dependencies:
694699
tweetnacl "^0.14.3"
695700

701+
bcrypt@^3.0.6:
702+
version "3.0.6"
703+
resolved "https://registry.yarnpkg.com/bcrypt/-/bcrypt-3.0.6.tgz#f607846df62d27e60d5e795612c4f67d70206eb2"
704+
integrity sha512-taA5bCTfXe7FUjKroKky9EXpdhkVvhE5owfxfLYodbrAR1Ul3juLmIQmIQBK4L9a5BuUcE6cqmwT+Da20lF9tg==
705+
dependencies:
706+
nan "2.13.2"
707+
node-pre-gyp "0.12.0"
708+
696709
bignumber.js@7.2.1:
697710
version "7.2.1"
698711
resolved "https://registry.yarnpkg.com/bignumber.js/-/bignumber.js-7.2.1.tgz#80c048759d826800807c4bfd521e50edbba57a5f"
@@ -2975,7 +2988,7 @@ mysql@^2.17.1:
29752988
safe-buffer "5.1.2"
29762989
sqlstring "2.3.1"
29772990

2978-
nan@^2.12.1:
2991+
nan@2.13.2, nan@^2.12.1:
29792992
version "2.13.2"
29802993
resolved "https://registry.yarnpkg.com/nan/-/nan-2.13.2.tgz#f51dc7ae66ba7d5d55e1e6d4d8092e802c9aefe7"
29812994
integrity sha512-TghvYc72wlMGMVMluVo9WRJc0mB8KxxF/gZ4YYFy7V2ZQX9l7rgbPg7vjS9mt6U5HXODVFVI2bOduCzwOMv/lw==
@@ -3047,7 +3060,7 @@ node-notifier@^5.2.1:
30473060
shellwords "^0.1.1"
30483061
which "^1.3.0"
30493062

3050-
node-pre-gyp@^0.12.0:
3063+
node-pre-gyp@0.12.0, node-pre-gyp@^0.12.0:
30513064
version "0.12.0"
30523065
resolved "https://registry.yarnpkg.com/node-pre-gyp/-/node-pre-gyp-0.12.0.tgz#39ba4bb1439da030295f899e3b520b7785766149"
30533066
integrity sha512-4KghwV8vH5k+g2ylT+sLTjy5wmUOb9vPhnM8NHvRf9dHmnW/CndrFXy2aRPaPST6dugXSdHXfeaHQm77PIz/1A==

0 commit comments

Comments
 (0)