Skip to content

Commit

Permalink
Updates to app
Browse files Browse the repository at this point in the history
  • Loading branch information
diberry committed May 3, 2022
1 parent 4156489 commit 5d808c1
Show file tree
Hide file tree
Showing 6 changed files with 143 additions and 26 deletions.
7 changes: 6 additions & 1 deletion 3-Add-cosmosdb-mongodb/.devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"dbaeumer.vscode-eslint",
"ms-azuretools.vscode-cosmosdb",
"ms-azuretools.vscode-azureappservice",
"mongodb.mongodb-vscode"
],

Expand All @@ -23,5 +25,8 @@
// "postCreateCommand": "yarn install",

// Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root.
"remoteUser": "node"
"remoteUser": "node",
"features": {
"azure-cli": "latest"
}
}
8 changes: 8 additions & 0 deletions 3-Add-cosmosdb-mongodb/controller/rentals.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@ import createError from 'http-errors';

// List view
export const viewAllRentals = async (req, res) => {

const appConnectedCorrectly = req.app.get('connected');
console.log(`App connected: ${JSON.stringify(appConnectedCorrectly)}`);

if(appConnectedCorrectly.status===false) {
return res.render('error', {status: 500, message: appConnectedCorrectly.err});
}

const rentals = await getRentals();

res.render('list', {
Expand Down
75 changes: 75 additions & 0 deletions 3-Add-cosmosdb-mongodb/insert.mongodb
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// MongoDB Playground
// To disable this template go to Settings | MongoDB | Use Default Template For Playground.
// Make sure you are connected to enable completions and to be able to run a playground.
// Use Ctrl+Space inside a snippet or a string literal to trigger completions.

// Select the database to use.
use('js-rentals');

// The drop() command destroys all data from a collection.
// Make sure you run it against the correct database and collection.
db.rentals.drop();

// Insert a few documents into the rentals collection.
db.rentals.insertMany([
{
"name": "Georgian Court",
"description": "lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quaerat.",
"image": "https://picsum.photos/200",
"price": "1000000",
"location": "San Francisco, CA",
"bedrooms": "3",
"bathrooms": "2",
"link": "http://www.example.com"
},
{
"name": "Brittany Court",
"description": "lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quaerat.",
"image": "https://picsum.photos/200",
"price": "3000000",
"location": "San Francisco, CA",
"bedrooms": "3",
"bathrooms": "2",
"link": "http://www.example.com"
},
{
"name": "Baz Homes",
"description": "lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quaerat.",
"image": "https://picsum.photos/200",
"price": "9000000",
"location": "San Francisco, CA",
"bedrooms": "3",
"bathrooms": "2",
"link": "http://www.example.com"
},
{
"name": "Bar Homes",
"description": "lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quaerat.",
"image": "https://picsum.photos/200",
"price": "4000000",
"location": "San Francisco, CA",
"bedrooms": "3",
"bathrooms": "2",
"link": "http://www.example.com"
},
{
"name": "Foo Homes",
"description": "lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quaerat.",
"image": "https://picsum.photos/200",
"price": "100000",
"location": "San Francisco, CA",
"bedrooms": "3",
"bathrooms": "2",
"link": "http://www.example.com"
},
{
"name": "Foo Hall",
"description": "lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quaerat.",
"image": "https://picsum.photos/200",
"price": "600000",
"location": "San Francisco, CA",
"bedrooms": "1",
"bathrooms": "2",
"link": "http://www.example.com"
}
]);
70 changes: 50 additions & 20 deletions 3-Add-cosmosdb-mongodb/model/rental.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,6 @@ const mongodbConnectionUrl = process.env.MONGODB_URI_CONNECTION_STRING;
const mongodbDatabaseName = process.env.MONGODB_URI_DATABASE_NAME;
const mongodbCollectionName = process.env.MONGODB_URI_COLLECTION_NAME;

if(!mongodbConnectionUrl
|| !mongodbDatabaseName
|| !mongodbCollectionName) throw new Error("Missing MongoDB connection information");

let client;
let database;
let rentalsCollection;
Expand Down Expand Up @@ -53,28 +49,62 @@ export const addRental = async (rental) => {
// Update one rental
// Only handles database, image changes are handled in controller
export const updateRental = async (rental) => {
return await rentalsCollection.updateOne({ _id: rental.id }, { $set: rental });
console.log(rental);
const response = await rentalsCollection.updateOne({ _id: new ObjectId(rental.id) }, { $set: rental });
console.log(response);
return response;
};
// Create database connection
export const connectToDatabase = async () => {

if (!client || !database || !rentalsCollection) {
// connect
client = await MongoClient.connect(mongodbConnectionUrl, {
useUnifiedTopology: true,
});

// get database
database = client.db(mongodbDatabaseName);
try{

// create collection if it doesn't exist
const collections = await database.listCollections().toArray();
const collectionExists = collections.filter((collection) => collection.name === mongodbCollectionName);
if (!collectionExists) {
await database.createCollection(mongodbCollectionName);
if(!mongodbConnectionUrl || !mongodbDatabaseName || !mongodbCollectionName){
return {
status: false,
err: 'Missing required params to begin database connection'
};
}

// get collection
rentalsCollection = await database.collection(mongodbCollectionName);
// if not connected, go ahead and connect
if (!client || !database || !rentalsCollection) {

console.log("(Re)Established connection to database");

// connect
client = await MongoClient.connect(mongodbConnectionUrl, {
useUnifiedTopology: true,
});

// get database
database = client.db(mongodbDatabaseName);

// create collection if it doesn't exist
const collections = await database.listCollections().toArray();
const collectionExists = collections.filter((collection) => collection.name === mongodbCollectionName);
if (!collectionExists) {
await database.createCollection(mongodbCollectionName);
}

// get collection
rentalsCollection = await database.collection(mongodbCollectionName);
return {
status: true,
action: "(Re)Established connection to database"
};
} else {
console.log('Already connected');
return {
status: true,
action: "Already connected"
};
}
}catch(err){
console.log(err);
return {
status: false,
err
}
}

};
7 changes: 4 additions & 3 deletions 3-Add-cosmosdb-mongodb/services/httpserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ export default async (app) => {
// http://locahost:3000 (no trailing slash)
app.use(checkTrailingSlash);

// Connect to Database
const connected = await connectToDatabase();
app.set('connected', connected);

// EJS Views
app.get('/', viewAllRentals);
app.get('/rental/edit/:id', viewEditRental);
Expand All @@ -86,8 +90,5 @@ export default async (app) => {
app.use(on404Error);
app.use(onRouteErrors);

// Connect to Database
await connectToDatabase();

return app;
};
2 changes: 0 additions & 2 deletions 3-Add-cosmosdb-mongodb/views/__layout/header.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@
<body>
<nav class="navbar navbar-light bg-light">
<a class="navbar-brand" href="/">
<img src="https://cloudmembers.logicom.net/wp-content/uploads/2018/06/Solution-image-4.png" width="30" height="30" class="d-inline-block align-top" alt="">
Azure Rental App
</a>
</nav>

<main class="container-fluid p-3">

0 comments on commit 5d808c1

Please sign in to comment.