Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add static pages and user management #155

Open
wants to merge 14 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions .github/workflows/linter.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
name: 'Lint Code'

on:
push:
branches: [master, main]
pull_request:
branches: [master, main]
on: workflow_dispatch

jobs: # list of things to do
lint_function_js:
Expand Down
63 changes: 63 additions & 0 deletions functions/get-dealership.js
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: 'u8v-rk2sni64qWz9lvYJLcbSw6NqgS27ijwCR4oVHhXu' } }, // Replace with your IAM API key
url: 'https://e5c1f382-d6e3-4c53-b67f-a2e45ce95497-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}`);
});
72 changes: 72 additions & 0 deletions functions/reviews.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
from cloudant.client import Cloudant
from cloudant.query import Query
from flask import Flask, jsonify, request
import atexit

#Add your Cloudant service credentials here
cloudant_username = 'e5c1f382-d6e3-4c53-b67f-a2e45ce95497-bluemix'
cloudant_api_key = 'u8v-rk2sni64qWz9lvYJLcbSw6NqgS27ijwCR4oVHhXu'
cloudant_url = 'https://e5c1f382-d6e3-4c53-b67f-a2e45ce95497-bluemix.cloudantnosqldb.appdomain.cloud'
client = Cloudant.iam(cloudant_username, cloudant_api_key, connect=True, url=cloudant_url)

session = client.session()
print('Databases:', client.all_dbs())

db = client['reviews']

app = Flask(__name__)

@app.route('/api/get_reviews', methods=['GET'])
def get_reviews():
dealership_id = request.args.get('id')

# Check if "id" parameter is missing
if dealership_id is None:
return jsonify({"error": "Missing 'id' parameter in the URL"}), 400

# Convert the "id" parameter to an integer (assuming "id" should be an integer)
try:
dealership_id = int(dealership_id)
except ValueError:
return jsonify({"error": "'id' parameter must be an integer"}), 400

# Define the query based on the 'dealership' ID
selector = {
'dealership': dealership_id
}

# Execute the query using the query method
result = db.get_query_result(selector)

# Create a list to store the documents
data_list = []

# Iterate through the results and add documents to the list
for doc in result:
data_list.append(doc)

# Return the data as JSON
return jsonify(data_list)


@app.route('/api/post_review', methods=['POST'])
def post_review():
if not request.json:
abort(400, description='Invalid JSON data')

# Extract review data from the request JSON
review_data = request.json

# Validate that the required fields are present in the review data
required_fields = ['id', 'name', 'dealership', 'review', 'purchase', 'purchase_date', 'car_make', 'car_model', 'car_year']
for field in required_fields:
if field not in review_data:
abort(400, description=f'Missing required field: {field}')

# Save the review data as a new document in the Cloudant database
db.create_document(review_data)

return jsonify({"message": "Review posted successfully"}), 201

if __name__ == '__main__':
app.run(debug=True)
4 changes: 2 additions & 2 deletions functions/sample/nodejs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@
const { IamAuthenticator } = require("ibm-cloud-sdk-core");

function main(params) {
const authenticator = new IamAuthenticator({ apikey: params.IAM_API_KEY });
const authenticator = new IamAuthenticator({ apikey: "u8v-rk2sni64qWz9lvYJLcbSw6NqgS27ijwCR4oVHhXu" });
const cloudant = CloudantV1.newInstance({
authenticator: authenticator,
});
cloudant.setServiceUrl(params.COUCH_URL);
cloudant.setServiceUrl("https://e5c1f382-d6e3-4c53-b67f-a2e45ce95497-bluemix.cloudantnosqldb.appdomain.cloud/");

let dbList = getDbs(cloudant);
return { dbs: dbList };
Expand Down
Loading