Skip to content

Commit

Permalink
Merge pull request #1 from appvia/initial
Browse files Browse the repository at this point in the history
feat: initial commit
  • Loading branch information
KashifSaadat authored Jul 3, 2024
2 parents fceea8f + 17ea496 commit fdb358b
Show file tree
Hide file tree
Showing 44 changed files with 31,658 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/pr.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Create and test a Docker image

on:
pull_request:
branches: ['main']

jobs:
build-and-test-image:
runs-on: ubuntu-latest
permissions:
contents: read

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Start containers
run: docker compose up --build --detach

- name: Run test
run: |
docker ps
for i in {1..10}; do curl -m 10 -s localhost:3000 | grep 'Appvia Todo List' && echo "[Attempt $i] Endpoint returned expected response." && exit 0 || echo "[Attempt $i] Endpoint not returning expected response, retrying in 5 seconds.." && sleep 5; done; exit 1
- name: Stop containers
run: docker compose down
64 changes: 64 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
name: Create and publish a Docker image

# Configures this workflow to run every time a change is pushed to the branch called `main`, or a version tag is pushed.
on:
push:
branches: ['main']
tags:
- 'v*'

# Defines two custom environment variables for the workflow. These are used for the Container registry domain, and a name for the Docker image that this workflow builds.
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}

# There is a single job in this workflow. It's configured to run on the latest available version of Ubuntu.
jobs:
build-and-push-image:
runs-on: ubuntu-latest
# Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job.
permissions:
contents: read
packages: write
attestations: write
id-token: write

steps:
- name: Checkout repository
uses: actions/checkout@v4

# Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here.
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

# This step uses [docker/metadata-action](https://github.com/docker/metadata-action#about) to extract tags and labels that will be applied to the specified image. The `id` "meta" allows the output of this step to be referenced in a subsequent step. The `images` value provides the base name for the tags and labels.
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

# This step uses the `docker/build-push-action` action to build the image, based on your repository's `Dockerfile`. If the build succeeds, it pushes the image to GitHub Packages.
# It uses the `context` parameter to define the build's context as the set of files located in the specified path.
# It uses the `tags` and `labels` parameters to tag and label the image with the output from the "meta" step.
- name: Build and push Docker image
id: push
uses: docker/build-push-action@v6
with:
context: ./app
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

# This step generates an artifact attestation for the image, which is an unforgeable statement about where and how it was built. It increases supply chain security for people who consume the image.
- name: Generate artifact attestation
uses: actions/attest-build-provenance@v1
with:
subject-name: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME}}
subject-digest: ${{ steps.push.outputs.digest }}
push-to-registry: true

9 changes: 9 additions & 0 deletions app/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# syntax=docker/dockerfile:1
FROM node:22-alpine
WORKDIR /app
COPY yarn.lock ./
COPY package.json ./
RUN yarn install --production
COPY . .
EXPOSE 3000
CMD ["node", "src/index.js"]
33 changes: 33 additions & 0 deletions app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "todo-app",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"prettify": "prettier -l --write \"**/*.js\"",
"test": "jest",
"dev": "nodemon src/index.js"
},
"dependencies": {
"express": "^4.17.1",
"mysql": "^2.18.1",
"sqlite3": "^5.0.0",
"uuid": "^3.3.3",
"wait-port": "^0.2.2"
},
"resolutions": {
"ansi-regex": "5.0.1"
},
"prettier": {
"trailingComma": "all",
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": true
},
"devDependencies": {
"jest": "^27.2.5",
"nodemon": "^2.0.13",
"prettier": "^1.18.2"
}
}
65 changes: 65 additions & 0 deletions app/spec/persistence/sqlite.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const db = require('../../src/persistence/sqlite');
const fs = require('fs');
const location = process.env.SQLITE_DB_LOCATION || '/etc/todos/todo.db';

const ITEM = {
id: '7aef3d7c-d301-4846-8358-2a91ec9d6be3',
name: 'Test',
completed: false,
};

beforeEach(() => {
if (fs.existsSync(location)) {
fs.unlinkSync(location);
}
});

test('it initializes correctly', async () => {
await db.init();
});

test('it can store and retrieve items', async () => {
await db.init();

await db.storeItem(ITEM);

const items = await db.getItems();
expect(items.length).toBe(1);
expect(items[0]).toEqual(ITEM);
});

test('it can update an existing item', async () => {
await db.init();

const initialItems = await db.getItems();
expect(initialItems.length).toBe(0);

await db.storeItem(ITEM);

await db.updateItem(
ITEM.id,
Object.assign({}, ITEM, { completed: !ITEM.completed }),
);

const items = await db.getItems();
expect(items.length).toBe(1);
expect(items[0].completed).toBe(!ITEM.completed);
});

test('it can remove an existing item', async () => {
await db.init();
await db.storeItem(ITEM);

await db.removeItem(ITEM.id);

const items = await db.getItems();
expect(items.length).toBe(0);
});

test('it can get a single item', async () => {
await db.init();
await db.storeItem(ITEM);

const item = await db.getItem(ITEM.id);
expect(item).toEqual(ITEM);
});
30 changes: 30 additions & 0 deletions app/spec/routes/addItem.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const db = require('../../src/persistence');
const addItem = require('../../src/routes/addItem');
const ITEM = { id: 12345 };
const uuid = require('uuid/v4');

jest.mock('uuid/v4', () => jest.fn());

jest.mock('../../src/persistence', () => ({
removeItem: jest.fn(),
storeItem: jest.fn(),
getItem: jest.fn(),
}));

test('it stores item correctly', async () => {
const id = 'something-not-a-uuid';
const name = 'A sample item';
const req = { body: { name } };
const res = { send: jest.fn() };

uuid.mockReturnValue(id);

await addItem(req, res);

const expectedItem = { id, name, completed: false };

expect(db.storeItem.mock.calls.length).toBe(1);
expect(db.storeItem.mock.calls[0][0]).toEqual(expectedItem);
expect(res.send.mock.calls[0].length).toBe(1);
expect(res.send.mock.calls[0][0]).toEqual(expectedItem);
});
20 changes: 20 additions & 0 deletions app/spec/routes/deleteItem.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const db = require('../../src/persistence');
const deleteItem = require('../../src/routes/deleteItem');
const ITEM = { id: 12345 };

jest.mock('../../src/persistence', () => ({
removeItem: jest.fn(),
getItem: jest.fn(),
}));

test('it removes item correctly', async () => {
const req = { params: { id: 12345 } };
const res = { sendStatus: jest.fn() };

await deleteItem(req, res);

expect(db.removeItem.mock.calls.length).toBe(1);
expect(db.removeItem.mock.calls[0][0]).toBe(req.params.id);
expect(res.sendStatus.mock.calls[0].length).toBe(1);
expect(res.sendStatus.mock.calls[0][0]).toBe(200);
});
19 changes: 19 additions & 0 deletions app/spec/routes/getItems.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const db = require('../../src/persistence');
const getItems = require('../../src/routes/getItems');
const ITEMS = [{ id: 12345 }];

jest.mock('../../src/persistence', () => ({
getItems: jest.fn(),
}));

test('it gets items correctly', async () => {
const req = {};
const res = { send: jest.fn() };
db.getItems.mockReturnValue(Promise.resolve(ITEMS));

await getItems(req, res);

expect(db.getItems.mock.calls.length).toBe(1);
expect(res.send.mock.calls[0].length).toBe(1);
expect(res.send.mock.calls[0][0]).toEqual(ITEMS);
});
33 changes: 33 additions & 0 deletions app/spec/routes/updateItem.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const db = require('../../src/persistence');
const updateItem = require('../../src/routes/updateItem');
const ITEM = { id: 12345 };

jest.mock('../../src/persistence', () => ({
getItem: jest.fn(),
updateItem: jest.fn(),
}));

test('it updates items correctly', async () => {
const req = {
params: { id: 1234 },
body: { name: 'New title', completed: false },
};
const res = { send: jest.fn() };

db.getItem.mockReturnValue(Promise.resolve(ITEM));

await updateItem(req, res);

expect(db.updateItem.mock.calls.length).toBe(1);
expect(db.updateItem.mock.calls[0][0]).toBe(req.params.id);
expect(db.updateItem.mock.calls[0][1]).toEqual({
name: 'New title',
completed: false,
});

expect(db.getItem.mock.calls.length).toBe(1);
expect(db.getItem.mock.calls[0][0]).toBe(req.params.id);

expect(res.send.mock.calls[0].length).toBe(1);
expect(res.send.mock.calls[0][0]).toEqual(ITEM);
});
32 changes: 32 additions & 0 deletions app/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const express = require('express');
const app = express();
const db = require('./persistence');
const getItems = require('./routes/getItems');
const addItem = require('./routes/addItem');
const updateItem = require('./routes/updateItem');
const deleteItem = require('./routes/deleteItem');

app.use(express.json());
app.use(express.static(__dirname + '/static'));

app.get('/items', getItems);
app.post('/items', addItem);
app.put('/items/:id', updateItem);
app.delete('/items/:id', deleteItem);

db.init().then(() => {
app.listen(3000, () => console.log('Listening on port 3000'));
}).catch((err) => {
console.error(err);
process.exit(1);
});

const gracefulShutdown = () => {
db.teardown()
.catch(() => {})
.then(() => process.exit());
};

process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
process.on('SIGUSR2', gracefulShutdown); // Sent by nodemon
2 changes: 2 additions & 0 deletions app/src/persistence/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
if (process.env.MYSQL_HOST) module.exports = require('./mysql');
else module.exports = require('./sqlite');
Loading

0 comments on commit fdb358b

Please sign in to comment.