GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — add changes :hamburger: · jozhetak/fullstack-javascript@b327871

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • chapter7
    • chapter7.md
  • code
    • 07-board-api-mongo
      • .gitignore
      • Procfile
      • package-lock.json
      • package.json
      • web.js
    • 07-db-connect-heroku
    • 07-db-server
      • Procfile
      • app.js
      • collections.js
      • package.json
    • 11-db-server
      • app.js
      • collections.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎chapter7/chapter7.md‎

Copy file name to clipboardExpand all lines: chapter7/chapter7.md
+100-99Lines changed: 100 additions & 99 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -209,29 +209,29 @@ from a Node.js script.
209209
After we install the library, we can include the `mongodb` library in
210210
our `app.js` file:
211211

212-
```
213-
var util = require('util')
214-
var mongodb = require ('mongodb')
212+
```js
213+
const util = require('util')
214+
const mongodb = require ('mongodb')
215215
```
216216

217217
This is one of the ways to establish connection to the MongoDB server in
218218
which the db variable will hold reference to the database at a specified
219219
host and port:
220220

221-
```
222-
var Db = mongodb.Db
223-
var Connection = mongodb.Connection
224-
var Server = mongodb.Server
225-
var host = '127.0.0.1'
226-
var port = 27017
221+
```js
222+
const Db = mongodb.Db
223+
const Connection = mongodb.Connection
224+
const Server = mongodb.Server
225+
const host = '127.0.0.1'
226+
const port = 27017
227227

228-
var db=new Db ('test', new Server(host,port, {}))
228+
const db = new Db ('test', new Server(host,port, {}))
229229
```
230230

231231
To actually open a connection:
232232

233-
```
234-
db.open(function(error, connection) {
233+
```js
234+
db.open((error, connection) => {
235235
// Do something with the database here
236236
db.close()
237237
})
@@ -241,14 +241,14 @@ To check that we have the connection, we need to handle `error`. Also,
241241
let's get the admin object with `db.admin()` and fetch the list of
242242
databases with `listDatabases()`:
243243

244-
```
245-
var db=new Db ('test', new Server(host, port, {}))
246-
db.open(function(error, connection){
244+
```js
245+
const db = new Db ('test', new Server(host, port, {}))
246+
db.open((error, connection) => {
247+
console.log('error: ', error)
248+
const adminDb = db.admin()
249+
adminDb.listDatabases((error, dbs) => {
247250
console.log('error: ', error)
248-
var adminDb = db.admin()
249-
adminDb.listDatabases(function(error, dbs) {
250-
console.log('error: ', error)
251-
console.log('databases: ', dbs.databases)
251+
console.log('databases: ', dbs.databases)
252252
db.close()
253253
})
254254
})
@@ -303,7 +303,7 @@ object:
303303

304304
or
305305

306-
`var connectionUri = url.parse(process.env.MONGOLAB_URI)`
306+
`const connectionUri = url.parse(process.env.MONGOLAB_URI)`
307307

308308
The global object process gives access to environment variables via
309309
`process.env`. Those variables conventionally used to pass database host
@@ -314,35 +314,35 @@ To make our code work both locally and on Heroku, we can use the logical
314314
OR operator `||` and assign a local host and port if environment
315315
variables are undefined:
316316

317-
```
318-
var port = process.env.PORT || 1337
319-
var dbConnUrl = process.env.MONGOLAB_URI ||
317+
```js
318+
const port = process.env.PORT || 1337
319+
const dbConnUrl = process.env.MONGOLAB_URI ||
320320
'mongodb://127.0.0.1:27017/test'
321321
```
322322

323323
Here is our updated cross-environment ready `app.js` file
324-
(https://github.com/azat-co/fullstack-javascript/tree/master/code/10-db-connect-heroku).
324+
(https://github.com/azat-co/fullstack-javascript/tree/master/code/07-db-connect-heroku).
325325
I added a method to get the list of collections `listCollections`
326326
instead of getting the list of the databases (we have only one database
327327
in MongoLab right now):
328328

329-
```
330-
var util = require('util')
331-
var url = require('url')
332-
var client = require ('mongodb').MongoClient
329+
```js
330+
const util = require('util')
331+
const url = require('url')
332+
const client = require ('mongodb').MongoClient
333333

334-
var dbConnUrl = process.env.MONGOLAB_URI ||
334+
const dbConnUrl = process.env.MONGOLAB_URI ||
335335
'mongodb://127.0.0.1:27017/test'
336336

337337
console.log('db server: ', dbConnUrl)
338338

339-
client.connect(dbConnUrl, {}, function(error, db){
339+
client.connect(dbConnUrl, {}, (error, db) => {
340+
console.log('error: ', error)
341+
db.listCollections().toArray((err, collections) => {
340342
console.log('error: ', error)
341-
db.listCollections().toArray(function(err, collections) {
342-
console.log('error: ', error)
343-
console.log('collections: ', collections)
343+
console.log('collections: ', collections)
344344
db.close()
345-
})
345+
})
346346
})
347347
```
348348

@@ -381,7 +381,7 @@ Heroku app, if you know the name of that app.
381381

382382
The project folder needs to have `Procfile` and `package.json`. You can
383383
copy them from
384-
https://github.com/azat-co/fullstack-javascript/tree/master/code/10-db-connect-heroku.
384+
https://github.com/azat-co/fullstack-javascript/tree/master/code/07-db-connect-heroku.
385385

386386
Now you can push you code to Heroku with:
387387

@@ -412,22 +412,22 @@ server object instantiation in a database connection callback (file
412412
Supplemental video which walks you through the implementation and
413413
demonstrates the project: <http://bit.ly/1Qnrmwr>.
414414

415-
```
416-
var util = require('util')
417-
var url = require('url')
418-
var http = require('http')
419-
var mongodb = require ('mongodb')
420-
var client = require ('mongodb').MongoClient
415+
```js
416+
const util = require('util')
417+
const url = require('url')
418+
const http = require('http')
419+
const mongodb = require ('mongodb')
420+
const client = require ('mongodb').MongoClient
421421

422-
var port = process.env.PORT || 1337
423-
var dbConnUrl = process.env.MONGOLAB_URI || 'mongodb://@127.0.0.1:27017/test'
422+
const port = process.env.PORT || 1337
423+
const dbConnUrl = process.env.MONGOLAB_URI || 'mongodb://@127.0.0.1:27017/test'
424424

425425
client.connect(dbConnUrl, {}, function(error, db) {
426426
console.log('error: ', error)
427427
db.listCollections().toArray(function(error, collections) {
428428
console.log('error: ', error)
429429
console.log('collections: ', collections)
430-
var server = http.createServer(function (request, response) { // Creates server
430+
const server = http.createServer(function (request, response) { // Creates server
431431
response.writeHead(200, {'Content-Type': 'text/plain'}) // Sets the right header and status code
432432
response.end(util.inspect(collections)) // Outputs string with line end symbol
433433
})
@@ -440,7 +440,7 @@ client.connect(dbConnUrl, {}, function(error, db) {
440440
```
441441

442442
The final Heroku-deployment-ready project is located at
443-
https://github.com/azat-co/fullstack-javascript/tree/master/code/11-db-serverunder.
443+
https://github.com/azat-co/fullstack-javascript/tree/master/code/07-db-serverunder.
444444

445445
After the deployment you should be able to open the URL provided by
446446
Heroku and see the list of collections. If it's a newly created app with
@@ -460,28 +460,28 @@ http://bit.ly/1QnsfoE.
460460
We should have everything set up for writing the Node.js application
461461
that will work both locally and on Heroku. The source code is available
462462
at
463-
https://github.com/azat-co/fullstack-javascript/tree/master/code/12-board-api-mongonder.
463+
<https://github.com/azat-co/fullstack-javascript/tree/master/code/07-board-api-mongo>.
464464
The structure of the application is simple:
465465

466466
```
467-
/12-board-api-mongo
467+
/07-board-api-mongo
468468
web.js
469469
Procfile
470470
package.json
471471
```
472472

473473
This is what `web.js` looks like; first we include our libraries:
474474

475-
```
476-
var http = require('http')
477-
var util = require('util')
478-
var querystring = require('querystring')
479-
var client = require('mongodb').MongoClient
475+
```js
476+
const http = require('http')
477+
const util = require('util')
478+
const querystring = require('querystring')
479+
const client = require('mongodb').MongoClient
480480
```
481481

482482
Then put out a magic string to connect to MongoDB:
483483

484-
`var uri = process.env.MONGOLAB_URI || 'mongodb://@127.0.0.1:27017/messages'`
484+
`const uri = process.env.MONGOLAB_URI || 'mongodb://@127.0.0.1:27017/messages'`
485485

486486
Note: The URI/URL format contains the optional database name in which
487487
our collection will be stored. Feel free to change it to something else:
@@ -490,79 +490,80 @@ for example, 'rpjs' or 'test'.
490490
We put all the logic inside of an open connection in the form of a
491491
callback function:
492492

493-
```
494-
client.connect(uri, function(error, db) {
493+
```js
494+
client.connect(uri, (error, db) => {
495495
if (error) return console.error(error)
496496
```
497497
498498
We are getting the collection with the next statement:
499499
500-
`var collection = db.collection('messages')`
500+
`const collection = db.collection('messages')`
501501
502502
Now we can instantiate the server and set up logic to process our
503503
endpoints/routes. We need to fetch the documents on GET
504-
`/messages/``list.json`:
505-
506-
```
507-
var app = http.createServer( function (request, response) {
508-
if (request.method === 'GET' && request.url === '/messages/list.json') {
509-
collection.find().toArray(function(error,results) {
510-
response.writeHead(200,{ 'Content-Type': 'text/plain'})
511-
console.dir(results)
512-
response.end(JSON.stringify(results))
513-
})
514-
```
515-
516-
On the POST `/messages/create.json`, we inserting the document:
517-
518-
```
519-
} else if (request.method === 'POST' && request.url === '/messages/create.json') {
520-
request.on('data', function(data) {
521-
collection.insert(querystring.parse(data.toString('utf-8')), {safe:true}, function(error, obj) {
522-
if (error) throw error
523-
response.end(JSON.stringify(obj))
524-
})
525-
})
526-
} else {
504+
`/messages/list.json`:
505+
506+
```js
507+
const app = http.createServer((request, response) => {
508+
if (request.method === 'GET' && request.url === '/messages.json') {
509+
collection.find().toArray((error,results) => {
510+
response.writeHead(200,{ 'Content-Type': 'text/plain'})
511+
console.dir(results)
512+
response.end(JSON.stringify(results))
513+
})
514+
```
515+
516+
On the POST `/messages.json`, we inserting the document:
517+
518+
```js
519+
} else if (request.method === 'POST' && request.url === '/messages.json') {
520+
request.on('data', function(data) {
521+
collection.insert(querystring.parse(data.toString('utf-8')), {safe:true}, function (error, obj) {
522+
if (error) throw error
523+
response.end(JSON.stringify(obj))
524+
})
525+
})
526+
} else {
527527
```
528528
529529
This will be shown in the event that the client request is not matching
530530
any of the conditions above. This is a good reminder for us when we try
531531
to go to the http://localhost:1337 instead of
532-
http://localhost:1337/messages/list.json:
533-
534-
```
535-
response.end('Supported endpoints: \n/messages/list.json\n/messages/create.json')
536-
}
537-
})
538-
var port = process.env.PORT || 1337
539-
app.listen(port)
532+
<http://localhost:1337/messages.json>:
533+
534+
```js
535+
response.end('Supported endpoints: \n/messages.json\n/messages.json')
536+
}
537+
})
538+
const port = process.env.PORT || 1337
539+
app.listen(port)
540540
})
541541
```
542542

543543
Note: We don't have to use additional words after the collection/entity
544-
name; that is, instead of `/`messages/list.json and
545-
/messages/create.json it's perfectly fine to have just `/messages` for
546-
all the HTTP methods such as GET, POST, PUT, DELETE. If you change them
547-
in your application code make sure to use the updated CURL commands and
544+
name; that is, instead of `/messages.json` it's perfectly fine to have just `/messages` for
545+
all the HTTP methods such as GET, POST, PUT, DELETE. The main reason why many developers and I use `.json` is to be explicit with the format which needs to be returned back. If you change them in your application code make sure to use the updated CURL commands and
548546
front-end code.
549547

550548
To test via CURL terminal commands run:
551549

552-
`$ curl http://localhost:5000/messages/list.json`
550+
`$ curl http://localhost:5000/messages.json`
553551

554-
Or open your browser at the http://locahost:1337/messages/list.json
555-
location.
552+
Or open your browser at the <http://locahost:1337/messages.json> location.
556553

557554
It should give you an empty array: `[]`, which is fine. Then POST a
558555
new message:
559556

560-
`$ curl -d "username=BOB&message=test" http://localhost:5000/messages/create.json`
557+
`$ curl -d "username=BOB&message=test" http://localhost:5000/messages.json`
561558

562559
Now we must see a response containing an ObjectID of a newly created
563560
element, for example:
564-
[{"username":"BOB","message":"test","_id":"51edcad45862430000000001"}].
565-
Your ObjectId might vary.
561+
562+
```
563+
[{"username":"BOB","message":"test","_id":"51edcad45862430000000001"}]
564+
```
565+
566+
Your ObjectId will be different. :-)
566567

567568
If everything works as it should locally, try to deploy it to Heroku.
568569

@@ -572,9 +573,9 @@ To test the application on Heroku, you could use the same
572573
or "http://127.0.0.1" with your unique Heroku app's host/URL:
573574

574575
```
575-
$ curl http://your-app-name.herokuapp.com/messages/list.json
576+
$ curl http://your-app-name.herokuapp.com/messages.json
576577
$ curl -d "username=BOB&message=test"
577-
http://your-app-name.herokuapp.com/messages/create.json
578+
http://your-app-name.herokuapp.com/messages.json
578579
```
579580

580581
It's also nice to double check the database either via Mongo shell:
Collapse file

‎code/12-board-api-mongo/.gitignore‎ ‎code/07-board-api-mongo/.gitignore‎code/12-board-api-mongo/.gitignore renamed to code/07-board-api-mongo/.gitignore

Copy file name to clipboard
File renamed without changes.
Collapse file

‎code/12-board-api-mongo/Procfile‎ ‎code/07-board-api-mongo/Procfile‎code/12-board-api-mongo/Procfile renamed to code/07-board-api-mongo/Procfile

Copy file name to clipboard
File renamed without changes.

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.