Skip to content

Commit 5afad14

Browse files
author
Thiago Bezerra
committed
refactor: create some constants to avoid hardcoded values
1 parent ed8da3d commit 5afad14

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

index.js

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,37 @@
11
const jwt = require("jsonwebtoken");
22

3-
// Constants.
3+
// JWT constants.
44
const JWT_PRIVATE_KEY = process.env.JWT_PRIVATE_KEY;
5-
const JWT_EXPIRATION_TIME = "1h";
5+
const JWT_EXPIRATION_TIME_IN_HOURS = "1h";
6+
const JWT_RS256_ALGORITHM = "RS256";
7+
8+
// HTTP constants.
9+
const HTTP_SUCCESS_STATUS_CODE = 200;
10+
const HTTP_BAD_REQUEST_STATUS_CODE = 400;
11+
const HTTP_INTERNAL_SERVER_ERROR_STATUS_CODE = 500;
12+
const HTTP_HEADER_CONTENT_TYPE_KEY = "content-type";
13+
const HTTP_HEADER_JSON_CONTENT_TYPE = "application/json";
14+
15+
// General constants.
16+
const STRING_TYPE = "string";
617

718
exports.handler = async (event) => {
819
try {
920
// Gets event body.
1021
const body =
11-
typeof event.body === "string" ? JSON.parse(event.body) : event.body;
22+
typeof event.body === STRING_TYPE ? JSON.parse(event.body) : event.body;
1223

1324
// Client will be identified by national id.
1425
const nationalId = body.nationalId;
1526

1627
if (!nationalId) {
1728
return {
18-
statusCode: 400,
29+
statusCode: HTTP_BAD_REQUEST_STATUS_CODE,
1930
};
2031
}
2132
} catch (error) {
2233
return {
23-
statusCode: 400,
34+
statusCode: HTTP_BAD_REQUEST_STATUS_CODE,
2435
};
2536
}
2637

@@ -39,8 +50,8 @@ exports.handler = async (event) => {
3950
sub: 1111111111,
4051
},
4152
options: {
42-
expiresIn: JWT_EXPIRATION_TIME,
43-
algorithm: "RS256",
53+
expiresIn: JWT_EXPIRATION_TIME_IN_HOURS,
54+
algorithm: JWT_RS256_ALGORITHM,
4455
},
4556
};
4657

@@ -52,14 +63,15 @@ exports.handler = async (event) => {
5263
);
5364

5465
return {
55-
headers: { "content-type": "application/json" },
56-
statusCode: 200,
66+
headers: {
67+
[HTTP_HEADER_CONTENT_TYPE_KEY]: HTTP_HEADER_JSON_CONTENT_TYPE,
68+
},
69+
statusCode: HTTP_SUCCESS_STATUS_CODE,
5770
body: JSON.stringify({ token }),
5871
};
5972
} catch (error) {
6073
return {
61-
statusCode: 500,
62-
body: "asd " + error,
74+
statusCode: HTTP_INTERNAL_SERVER_ERROR_STATUS_CODE,
6375
};
6476
}
6577
};

0 commit comments

Comments
 (0)