Skip to content

Commit

Permalink
answerservice v0
Browse files Browse the repository at this point in the history
  • Loading branch information
angelalvaigle committed Mar 3, 2024
1 parent a6f8bb8 commit 1cd7294
Show file tree
Hide file tree
Showing 12 changed files with 5,726 additions and 20 deletions.
18 changes: 17 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ services:
environment:
MONGODB_URI: mongodb://mongodb:27017/userdb

answerservice:
container_name: answerservice-${teamname:-defaultASW}
image: ghcr.io/arquisoft/wiq_es6a/answerservice:latest
profiles: ["dev", "prod"]
build: ./questions/answerservice
depends_on:
- mongodb
ports:
- "8004:8004"
networks:
- mynetwork
environment:
MONGODB_URI: mongodb://mongodb:27017/answerdb

gatewayservice:
container_name: gatewayservice-${teamname:-defaultASW}
image: ghcr.io/arquisoft/wiq_es6a/gatewayservice:latest
Expand All @@ -48,13 +62,15 @@ services:
- mongodb
- userservice
- authservice
- answerservice
ports:
- "8000:8000"
networks:
- mynetwork
environment:
AUTH_SERVICE_URL: http://authservice:8002
USER_SERVICE_URL: http://userservice:8001
AUTH_SERVICE_URL: http://authservice:8002
ANSWER_SERVICE_URL: http://answerservice:8004

webapp:
container_name: webapp-${teamname:-defaultASW}
Expand Down
24 changes: 23 additions & 1 deletion gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ const promBundle = require('express-prom-bundle');
const app = express();
const port = 8000;

const authServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8002';
const userServiceUrl = process.env.USER_SERVICE_URL || 'http://localhost:8001';
const authServiceUrl = process.env.AUTH_SERVICE_URL || 'http://localhost:8002';

const answerServiceUrl = process.env.ANSWER_SERVICE_URL || 'http://localhost:8004';

app.use(cors());
app.use(express.json());
Expand Down Expand Up @@ -41,6 +43,26 @@ app.post('/adduser', async (req, res) => {
}
});

app.post('/addanswer', async (req, res) => {
try {
// Forward the add answer request to the answer service
const answerResponse = await axios.post(answerServiceUrl+'/addanswer', req.body);
res.json(answerResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
}
});

app.post('/getanswer', async (req, res) => {
try {
// Forward the add answer request to the answer service
const answerResponse = await axios.post(answerServiceUrl+'/getanswer', req.body);
res.json(answerResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
}
});

// Start the gateway service
const server = app.listen(port, () => {
console.log(`Gateway Service listening at http://localhost:${port}`);
Expand Down
2 changes: 2 additions & 0 deletions questions/answerservice/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
coverage
20 changes: 20 additions & 0 deletions questions/answerservice/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Use an official Node.js runtime as a parent image
FROM node:20

# Set the working directory in the container
WORKDIR /usr/src/answerservice

# Copy package.json and package-lock.json to the working directory
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the app source code to the working directory
COPY . .

# Expose the port the app runs on
EXPOSE 8004

# Define the command to run your app
CMD ["node", "answer-service.js"]
16 changes: 16 additions & 0 deletions questions/answerservice/answer-model.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const mongoose = require('mongoose');

const answerSchema = new mongoose.Schema({
type: {
type: String,
required: true,
},
value: {
type: String,
required: true,
},
});

const Answer = mongoose.model('Answer', answerSchema);

module.exports = Answer
77 changes: 77 additions & 0 deletions questions/answerservice/answer-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// answer-service.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const Answer = require('./answer-model')

const app = express();
const port = 8004;

// Middleware to parse JSON in request body
app.use(bodyParser.json());

// Connect to MongoDB
const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/answerdb';
mongoose.connect(mongoUri);

// Function to validate required fields in the request body
function validateRequiredFields(req, requiredFields) {
for (const field of requiredFields) {
if (!(field in req.body)) {
throw new Error(`Missing required field: ${field}`);
}
}
}

app.post('/addanswer', async (req, res) => {
try {
// Check if required fields are present in the request body
// validateRequiredFields(req, ['answername', 'password']);

// Encrypt the password before saving it
// const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newAnswer = new Answer({
type: req.body.type,
value: req.body.value,
});

await newAnswer.save();
res.json(newAnswer);
} catch (error) {
res.status(400).json({ error: error.message });
}
});

app.post('/getanswer', async (req, res) => {
try {
// Check if required fields are present in the request body
validateRequiredFields(req, ['type', 'value']);

const { type, value } = req.body;

// Find the answer by type in the database
const answer = await Answer.findOne({ value });

// Check if the answer exists
if (answer) {
// Respond with the answer information
res.json({ type: answer.type, value: answer.value });
} else {
res.status(401).json({ error: 'Answer not found' });
}
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' });
}
});

const server = app.listen(port, () => {
console.log(`Answer Service listening at http://localhost:${port}`);
});

// Listen for the 'close' event on the Express.js server
server.on('close', () => {
// Close the Mongoose connection
mongoose.connection.close();
});

module.exports = server
30 changes: 30 additions & 0 deletions questions/answerservice/answer-service.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const request = require('supertest');
const { MongoMemoryServer } = require('mongodb-memory-server');

let mongoServer;
let app;

beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
process.env.MONGODB_URI = mongoUri;
app = require('./user-service');
});

afterAll(async () => {
app.close();
await mongoServer.stop();
});

describe('User Service', () => {
it('should add a new user on POST /adduser', async () => {
const newUser = {
username: 'testuser',
password: 'testpassword',
};

const response = await request(app).post('/adduser').send(newUser);
expect(response.status).toBe(200);
expect(response.body).toHaveProperty('username', 'testuser');
});
});
Loading

0 comments on commit 1cd7294

Please sign in to comment.