Skip to content
Snippets Groups Projects
Commit d25de1be authored by Andrej Rasevic's avatar Andrej Rasevic
Browse files

adding exercise4

parent 56bc14fc
No related branches found
No related tags found
No related merge requests found
Showing
with 906 additions and 0 deletions
.DS_Store
node_modules/
\ No newline at end of file
#!/usr/bin/env node
// require('../')()
const index = require('../index')
index()
//createContact.js
\ No newline at end of file
//deleteContact.js
\ No newline at end of file
//getContacts.js
\ No newline at end of file
//help.js
\ No newline at end of file
//updateContact.js
\ No newline at end of file
const minimist = require('minimist');
const axios = require('axios');
//uncomment this code to see a sample of making an axios get request
//axios.get('http://webcode.me').then(resp => {
//console.log(resp.data);
//});
\ No newline at end of file
{
"name": "contactsrestclient",
"version": "1.0.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"axios": {
"version": "0.21.1",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.1.tgz",
"integrity": "sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA==",
"requires": {
"follow-redirects": "^1.10.0"
}
},
"follow-redirects": {
"version": "1.13.1",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.13.1.tgz",
"integrity": "sha512-SSG5xmZh1mkPGyKzjZP8zLjltIfpW32Y5QpdNJyjcfGxK3qo3NDDkZOZSFiGn1A6SclQxY9GzEwAHQ3dmYRWpg=="
},
"minimist": {
"version": "1.2.5",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
}
}
}
{
"name": "contactsrestclient",
"version": "1.0.0",
"description": "Rest Client to interact with MyContacts API",
"main": "index.js",
"scripts": {
"start": "node bin/contactsclient",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"bin": {
"contactsclient": "bin/contactsclient"
},
"dependencies": {
"axios": "^0.21.1",
"minimist": "^1.2.5"
}
}
# Exercise 4: Connecting to Mongo Atlas/Building a Contacts API and a custom rest client
## Due Date: Thursday, January 21, 2021 11:59 PM
## Objectives: To connect to your Mongo Atlas instance and create a user that the teaching staff will have access to.
## Specifications/Requirements
1. We will be taking our in memory api example we developed in exercise 3 and now adding a connection to a real database to achieve data persistence. As such to complete this exercise you need to do the following:
* create a user on your Mongo Atlas instance that has Read and write to any database permission
* the user name should be `dbadmin`
* the password should be `dbpassword`
* using mongoose, in the `app.js` file inside of the `MyContacts` directory add the code to successfully connect to your database, which should be named `contacts`.
* create the schema for a Contact model. The fields should be the same as the ones in exercise 3.
* create a contacts router to define all of your endpoints in the `contactsRouter` module.
* create all of your handlers to pass to your routes in the `contactsController` module.
All the details should duplicate the functionality from exercise 3 - all you are doing now is adding data persistence to your api.
2. Additionally you will be creating a command line tool to interact with your api. For referecne look at the code example inside of the `week1` directory named `commandLineExample`. You will invoke your command line by running `npm start` . You need to create a command line utility that will parse the input on the command line and make the appropriate rest call to your api. Additionally you should define a help command that lets the user know how to invoke each command and what parameters each command takes. For example:
contactsclient [command] <options>
The <options> parameters should contain everything you need to make successful rest request of type [command]. You may find this helpful for what to pass to the axios client which you wil be using to make your rest calls:
<https://www.npmjs.com/package/axios#example>.
__Hint:__ Feel free to look at the code samples and use any snippets that may be helpful.
__Note:__ You will need to execute `npm install` inside of each of the top level directories to get all the necessary npm packages required in `package.json`. To submit your project you will need to commit your changes and push them to your remote gitlab repo. Always check online that you see your code after pushing to be sure that your solution is there.
\ No newline at end of file
.DS_Store
node_modules
\ No newline at end of file
const express = require('express');
const cors = require('cors');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const app = express();
// Set-up middleware stack
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const dbuser = 'dbadmin'
const dbpass = 'dbpassword'
// TODO
//Replace this connection string with your own instance
const mongoDB = `mongodb+srv://${dbuser}:${dbpass}@teaching-adb1b.mongodb.net/lectureExamples?retryWrites=true`;
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
module.exports = app;
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('mycontacts:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
//contactsController.js
\ No newline at end of file
// module to define schema for contact model
\ No newline at end of file
This diff is collapsed.
{
"name": "mycontacts",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"async": "^3.2.0",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"debug": "~2.6.9",
"express": "~4.16.1",
"mongoose": "^5.11.12",
"morgan": "~1.9.1"
}
}
<html>
<head>
<title>Express</title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Express</h1>
<p>Welcome to Express</p>
</body>
</html>
body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00B7FF;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment