Last active
April 30, 2021 16:31
-
-
Save yomigeek/5e8ebde075bb656e07e7ac99c94e578a to your computer and use it in GitHub Desktop.
NodeJS/Express code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Router } from "express"; | |
import AuthController from "../controllers/AuthController"; | |
const authRouter = Router(); | |
authRouter.post( | |
"/signup", | |
AuthController.userSignUp | |
); | |
export default authRouter; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AuthController { | |
static userSignUp(req, res, next) { | |
res.status(200).json({ | |
status: 'success', | |
message: 'signup sucessful', | |
}); | |
} | |
} | |
export default AuthController; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE IF NOT EXISTS users ( | |
id SERIAL, | |
userid VARCHAR (255) PRIMARY KEY, | |
firstname VARCHAR (100) NOT NULL, | |
lastname VARCHAR (100) NOT NULL, | |
email VARCHAR (255) UNIQUE NOT NULL, | |
phone VARCHAR (255) NOT NULL, | |
password VARCHAR (255) NOT NULL, | |
role VARCHAR (255) NOT NULL, | |
createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Pool} from "pg"; | |
import dotenv from "dotenv"; | |
dotenv.config(); | |
const mydatabase = process.env.DATABASE_URL; | |
// Or | |
// const pool = new Pool({ | |
// user: 'dbuser', | |
// host: 'database.server.com', | |
// database: 'mydb', | |
// password: 'secretpassword', | |
// port: 3211, | |
// }) | |
// check here https://node-postgres.com/features/connecting | |
const connect = new Pool({ | |
connectionString: mydatabase, | |
ssl: { rejectUnauthorized: false } | |
}); | |
connect.on('error', (err, client) => { | |
console.error('Error:', err); | |
}); | |
export default connect; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE IF NOT EXISTS orders ( | |
orderid int NOT NULL, | |
userid VARCHAR (2225), | |
PRIMARY KEY (orderid), | |
FOREIGN KEY (userid) REFERENCES users(userid) | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express(); | |
app.get('/', function (req, res) { | |
res.send('Hello World'); | |
}) | |
var server = app.listen(8081, function () { | |
var host = server.address().address | |
var port = server.address().port | |
console.log("Example app listening at http://%s:%s", host, port) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import jwt from "jsonwebtoken"; | |
import dotenv from "dotenv"; | |
dotenv.config(); | |
class Token { | |
/** | |
* @description Method to generate token | |
* | |
* @param {Object} user | |
* | |
* @return {String} Returned token | |
*/ | |
static generateToken(tokenData) { | |
return jwt.sign( | |
tokenData, | |
process.env.SECRET, | |
{ | |
expiresIn: tokenData.expiryTime | |
} | |
); | |
} | |
static verifyToken(req, res, next) { | |
const token = req.body.token || req.headers['x-access-token']; | |
if (token) { | |
jwt.verify(token, process.env.SECRET, (error, decoded) => { | |
if (error) { | |
return res.status(401).send({ | |
status: 'unauthorized', | |
statusCode: 401, | |
error | |
}); | |
} | |
req.decoded = decoded; | |
return next(); | |
}); | |
} else { | |
return res.status(401).send({ | |
status: 'unauthorized', | |
statusCode: 401, | |
message: 'Unauthorized Access! You are not allowed to access this resource.', | |
}); | |
} | |
} | |
} | |
export default Token; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// query data | |
connect.query( | |
`SELECT userid, email, firstname, lastname, role FROM users WHERE email='${formattedEmail}'`, | |
(err, response) => { | |
const result = JSON.parse(JSON.stringify(response.rows)); | |
///...more code here | |
return res.status(200).json({ | |
status: 'success', | |
statusCode: 200, | |
message: 'Login successful', | |
token: TokenUtils.generateToken(tokenData), | |
}); | |
} | |
); | |
// insert data | |
connect.query( | |
`${'insert into users (firstname, lastname, userId, email, password, role, phone, channel) ' + | |
"values ('"}${formattedFirstName}', '${formattedLastName}', '${userId}','${formattedEmail}','','user', '', 'facebook')`, | |
(err, response) => { | |
if (err) { | |
return AuthController.loginError(res); | |
} | |
const tokenData = { | |
userId: userId, | |
email: formattedEmail, | |
firstname: formattedFirstName, | |
lastname: formattedLastName, | |
role: 'user', | |
expiryTime: '4320h', | |
}; | |
return res.status(200).json({ | |
status: 'success', | |
statusCode: 200, | |
message: 'Login successful', | |
token: TokenUtils.generateToken(tokenData), | |
}); | |
} | |
); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'babel-core/register'; | |
import express from 'express'; | |
import cors from 'cors'; | |
import bodyParser from 'body-parser'; | |
import apiRoutes from './routes/index'; | |
import dotenv from 'dotenv'; | |
dotenv.config(); | |
// Setting up the express app | |
const app = express(); | |
const port = process.env.PORT || 5000; | |
app.use(cors()); | |
app.use(bodyParser.json()); | |
app.use(bodyParser.urlencoded({extended: true})); | |
app.use('/api/v1/', apiRoutes); | |
// catch un-available routes | |
app.all('*', (req, res) => { | |
res.status(404).json({ | |
status: 'error', | |
message: 'Oops! The resource you requested does not exist.', | |
}); | |
}); | |
app.listen(port, () => { | |
console.log(`server started at: ${port}`); | |
}); | |
export default app; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Router } from 'express'; | |
import authRouter from './auth'; | |
const apiRoutes = Router(); | |
apiRoutes.use('/auth', authRouter); | |
// Matches /api the API home route | |
apiRoutes.get('/', (req, res) => { | |
res.status(200).send({ | |
url: `${req.protocol}://${req.headers.host}`, | |
status: 'success', | |
message: "WELCOME TO MY API" | |
}); | |
}); | |
export default apiRoutes; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var app = express(); | |
// This responds with "Hello World" on the homepage | |
app.get('/', function (req, res) { | |
console.log("Got a GET request for the homepage"); | |
res.send('Hello GET'); | |
}) | |
// This responds a POST request for the homepage | |
app.post('/', function (req, res) { | |
console.log("Got a POST request for the homepage"); | |
res.send('Hello POST'); | |
}) | |
// This responds a DELETE request for the /del_user page. | |
app.delete('/del_user', function (req, res) { | |
console.log("Got a DELETE request for /del_user"); | |
res.send('Hello DELETE'); | |
}) | |
// This responds a GET request for the /list_user page. | |
app.get('/list_user', function (req, res) { | |
console.log("Got a GET request for /list_user"); | |
res.send('Page Listing'); | |
}) | |
// This responds a GET request for abcd, abxcd, ab123cd, and so on | |
app.get('/ab*cd', function(req, res) { | |
console.log("Got a GET request for /ab*cd"); | |
res.send('Page Pattern Match'); | |
}) | |
var server = app.listen(8081, function () { | |
var host = server.address().address | |
var port = server.address().port | |
console.log("Example app listening at http://%s:%s", host, port) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment