CRUD PostGRES



.......................................................................................................................................................................

                                        Full i have done but some error posted at github yet 

.......................................................................................................................................................................



link at the computer where i get the doc at Internet :  

https://medium.com/@olinations/build-a-crud-template-using-react-bootstrap-express-postgres-9f84cc444438


Project name in my computer :

~/projects/sample_cruds/rcwp/crudPractice-api/cpractice-frontend$


.......................................................................................................................................................................

                                                        Doc _Description Full


Build a CRUD Template Using React, Bootstrap, Express & Postgres




1. Setup the Backend

The plan…
Create express app, include all dependencies.
Create a postgres database and a db table within it.
Create a single page API that handles all the requests.

Take Action…
Command Line…

mkdir crudPractice-api
cd crudPractice-api
git init
mkdir controllers
subl .


NPM Installs…

npm init -y
npm install express body-parser pg knex dotenv helmet cors morgan
npm install nodemon --save-dev


Setup…
In the package.json file, do the following :

1. change the “name” to “Crud Practice”
2. change the “description” to “Practicing crud.”
3. replace the “main” line with…
“main”: “server.js”,
4. replace the scripts content with…
“start”: “nodemon server.js”

Add server.js file…
create server.js file in root directory
copy the contents of the code below to the new server.js file

............................................................ Server.js............................................................


const express = require('express')
// use process.env variables to keep private variables,
require('dotenv').config()
// Express Middleware
const helmet = require('helmet') // creates headers that protect from attacks (security)
const bodyParser = require('body-parser') // turns response into usable format
const cors = require('cors') // allows/disallows cross-site communication
const morgan = require('morgan') // logs requests
// db Connection w/ Heroku
// const db = require('knex')({
// client: 'pg',
// connection: {
// connectionString: process.env.DATABASE_URL,
// ssl: true,
// }
// });
// db Connection w/ localhost
var db = require('knex')({
client: 'pg',
connection: {
host : '127.0.0.1',
user : '',
password : '',
database : 'crud-practice-1'
}
});
// Controllers - aka, the db queries
const main = require('./controllers/main')
// App
const app = express()
// App Middleware
const whitelist = ['http://localhost:3001']
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(helmet())
app.use(cors(corsOptions))
app.use(bodyParser.json())
app.use(morgan('combined')) // use 'tiny' or 'combined'
// App Routes - Auth
app.get('/', (req, res) => res.send('hello world'))
app.get('/crud', (req, res) => main.getTableData(req, res, db))
app.post('/crud', (req, res) => main.postTableData(req, res, db))
app.put('/crud', (req, res) => main.putTableData(req, res, db))
app.delete('/crud', (req, res) => main.deleteTableData(req, res, db))
// App Server Connection
app.listen(process.env.PORT || 3000, () => {
console.log(`app is running on port ${process.env.PORT || 3000}`)
}) ................................................................................

the server.js file will now include:
- the express/app creation/connection/porting
- the postgres connection via knex
- all middleware
- api routes

Add the controller…
create main.js in the controllers folder
copy the contents of the code below into the new main.js file

............................................................................... main.js ...............................................................................
const getTableData = (req, res, db) => {
db.select('*').from('testtable1')
.then(items => {
if(items.length){
res.json(items)
} else {
res.json({dataExists: 'false'})
}
})
.catch(err => res.status(400).json({dbError: 'db error'}))
}
const postTableData = (req, res, db) => {
const { first, last, email, phone, location, hobby } = req.body
const added = new Date()
db('testtable1').insert({first, last, email, phone, location, hobby, added})
.returning('*')
.then(item => {
res.json(item)
})
.catch(err => res.status(400).json({dbError: 'db error'}))
}
const putTableData = (req, res, db) => {
const { id, first, last, email, phone, location, hobby } = req.body
db('testtable1').where({id}).update({first, last, email, phone, location, hobby})
.returning('*')
.then(item => {
res.json(item)
})
.catch(err => res.status(400).json({dbError: 'db error'}))
}
const deleteTableData = (req, res, db) => {
const { id } = req.body
db('testtable1').where({id}).del()
.then(() => {
res.json({delete: 'true'})
})
.catch(err => res.status(400).json({dbError: 'db error'}))
}
module.exports = {
getTableData,
postTableData,
putTableData,
deleteTableData
}

































Comments

Popular posts from this blog

Rails 7 Features :: Comparison with Rails 6 and Rails 5