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

adding exercise 4

parent bd24d400
No related branches found
No related tags found
No related merge requests found
Showing
with 962 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
const axios = require('axios');
const url = 'http://localhost:3000/api/v1/contacts'
module.exports = (args) => {
console.log('calling POST')
let {firstName, lastName, email} = args
console.log(args)
axios.post(url, {}).then(resp => {
console.log(resp.data);
});
}
\ No newline at end of file
//deleteContact.js
\ No newline at end of file
//getContacts.js
const axios = require('axios');
const url = 'http://localhost:3000/api/v1/contacts'
module.exports = (args) => {
console.log('calling GET')
console.log(args)
axios.get(url).then(resp => {
console.log(resp.data);
});
}
\ 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');
//uncomment this code to see a sample of making an axios get request
//axios.get('http://webcode.me').then(resp => {
//console.log(resp.data);
//});
module.exports = () => {
const args = minimist(process.argv.slice(2))
console.log("args is: ");
console.log(args);
//let cmd = args._[0] || 'help'
//if (args.help || args.h) {
//cmd = 'help'
//}
let request = args.request
console.log("------------")
console.log(request);
switch (request) {
case 'GET':
require('./cmds/getContacts')(args)
break
case 'POST':
require('./cmds/foo')
break
case 'PUT':
require('./cmds/version')(args)
break
case 'DELETE':
require('./cmds/help')(args)
break
default:
console.error(`"${cmd}" is not a valid command!`)
break
}
}
\ 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: Friday, January 21, 2021 11:59 PM
## Objectives: Create a Restful API that connects to hosted instance of Mongo
## 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:
* 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`. To do this update the placeholder in the connection string to mongo
with your directory id.
* 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 `node ./bin/contactsclient` . 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 }));
// TODO
//Update this connection string with your directory id inside of the brackets
const db = mongoose.connect('mongodb+srv://dbadmin:dbpassword@cmsc388b.a9mha.mongodb.net/<your_directory_id>-exercise4?retryWrites=true&w=majority',
{ useNewUrlParser: true, useUnifiedTopology: true})
.catch( err => console.error(err));
app.get('/api/v1/contacts', (req, res) => {
res.json({firstName: 'Andrej', lastName: 'Rasevic'})
})
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.13.13",
"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