-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
258037d
commit c1dc098
Showing
3 changed files
with
2,552 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
const express = require('express'); | ||
const app = express(); | ||
const port = process.env.PORT || 3000; | ||
const Cloudant = require('@cloudant/cloudant'); | ||
|
||
// Initialize Cloudant connection with IAM authentication | ||
async function dbCloudantConnect() { | ||
try { | ||
const cloudant = Cloudant({ | ||
plugins: { iamauth: { iamApiKey: 'lFnsCSKmd5_xobPHhDOqiEiAf8Cl5wzXIkl8fZE6XICX' } }, // Replace with your IAM API key | ||
url: 'https://6ddb1e63-c7db-4e0c-89fa-79730f4d208e-bluemix.cloudantnosqldb.appdomain.cloud', // Replace with your Cloudant URL | ||
}); | ||
|
||
const db = cloudant.use('dealerships'); | ||
console.info('Connect success! Connected to DB'); | ||
return db; | ||
} catch (err) { | ||
console.error('Connect failure: ' + err.message + ' for Cloudant DB'); | ||
throw err; | ||
} | ||
} | ||
|
||
let db; | ||
|
||
(async () => { | ||
db = await dbCloudantConnect(); | ||
})(); | ||
|
||
app.use(express.json()); | ||
|
||
// Define a route to get all dealerships with optional state and ID filters | ||
app.get('/dealerships/get', (req, res) => { | ||
const { state, id } = req.query; | ||
|
||
// Create a selector object based on query parameters | ||
const selector = {}; | ||
if (state) { | ||
selector.state = state; | ||
} | ||
|
||
if (id) { | ||
selector.id = parseInt(id); // Filter by "id" with a value of 1 | ||
} | ||
|
||
const queryOptions = { | ||
selector, | ||
limit: 10, // Limit the number of documents returned to 10 | ||
}; | ||
|
||
db.find(queryOptions, (err, body) => { | ||
if (err) { | ||
console.error('Error fetching dealerships:', err); | ||
res.status(500).json({ error: 'An error occurred while fetching dealerships.' }); | ||
} else { | ||
const dealerships = body.docs; | ||
res.json(dealerships); | ||
} | ||
}); | ||
}); | ||
|
||
app.listen(port, () => { | ||
console.log(`Server is running on port ${port}`); | ||
}); |
Oops, something went wrong.