Skip to content

Instantly share code, notes, and snippets.

@kaysush
Created September 20, 2022 04:19
Show Gist options
  • Save kaysush/4dd703d617838285a3aa5dc44a9ca53b to your computer and use it in GitHub Desktop.
Save kaysush/4dd703d617838285a3aa5dc44a9ca53b to your computer and use it in GitHub Desktop.
Backend service for Service to Service authentication demo in Cloud Run. Complete code is present at https://github.com/kaysush/cloud-run-s2s-demo/tree/main/backend
FROM node:16.13.1-stretch as build
WORKDIR /app
COPY package*.json /app/
# Install production dependencies
RUN npm install --only=production
RUN cp -a node_modules /tmp/prod_node_modules
# Now install all dependencies
RUN npm install
COPY . .
FROM gcr.io/distroless/nodejs:16
COPY --from=build --chown=nonroot:nonroot /tmp/prod_node_modules/ /app/node_modules/
WORKDIR /app
COPY . .
USER nonroot
CMD ["index.js"]
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express()
app.use(cors())
const port = process.env.PORT
// Configuring body parser middleware
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.get('/health', (req, res) => {
res.send("This is the health endpoint.")
})
app.post("/calculate", (req, res) => {
const request = req.body
const x = request.x
const y = request.y
const operator = request.op
switch(operator) {
case '+':
var result = x + y;
res.send(JSON.stringify({result : result}))
break;
case '-':
var result = x - y;
res.send(JSON.stringify({result : result}))
break;
case '*':
var result = x * y;
res.send(JSON.stringify({result : result}))
break;
case '/':
var result = x / y;
res.send(JSON.stringify({result : result}))
break;
default:
res.status(500).send(`Operator ${operator} not supported.`);
}
})
app.listen(port, () => console.log(`Backend started on port ${port}!`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment