Skip to content

Commit

Permalink
mongo implementation 🐺
Browse files Browse the repository at this point in the history
  • Loading branch information
0xheartcode committed Sep 18, 2024
1 parent db9f805 commit 8db8267
Show file tree
Hide file tree
Showing 12 changed files with 335 additions and 64 deletions.
1 change: 1 addition & 0 deletions .env.local
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
MAKEFILE_OVERWRITE_DOCKERNAME=
INITIAL_BEARER_TOKEN=
MONGO_URI=
11 changes: 4 additions & 7 deletions .github/workflows/prod-workflow.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
name: Prod - TALENTPLUG-MAIL-APP
name: Prod

on:
# push:
# branches:
# - prod
push:
branches:
- prod

jobs:
cloud_build-local_docker:
Expand All @@ -17,10 +17,7 @@ jobs:
uses: SpicyPizza/create-envfile@v2.0
with:
envkey_PORT: ${{ vars.ENVKEY_PORT }}
envkey_API_URL: ${{ vars.API_URL_PROD }} #Full api-core email endpoint here
envkey_INITIAL_REFRESH_TOKEN: ${{ vars.INITIAL_REFRESH_TOKEN }}
envkey_INITIAL_BEARER_TOKEN: ${{ vars.INITIAL_BEARER_TOKEN }}
envkey_INITIAL_GOOGLE_CREDENTIALS: ${{ vars.INITIAL_GOOGLE_CREDENTIALS }}
envkey_MAKEFILE_OVERWRITE_DOCKERNAME: ${{ vars.MAKEFILE_OVERWRITE_DOCKERNAME }}
sort_keys: false
file_name: .env.local
Expand Down
12 changes: 4 additions & 8 deletions .github/workflows/staging-workflow.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
name: Staging - TALENTPLUG-MAIL-APP
name: Staging

on:
# push:
# branches:
# - staging
push:
branches:
- staging
workflow_dispatch:
inputs:
reason:
Expand All @@ -24,10 +24,7 @@ jobs:
uses: SpicyPizza/create-envfile@v2.0
with:
envkey_PORT: ${{ vars.ENVKEY_PORT }}
envkey_API_URL: ${{ vars.API_URL_STAGING }} #Full api-core email endpoint here
envkey_INITIAL_REFRESH_TOKEN: ${{ vars.INITIAL_REFRESH_TOKEN }}
envkey_INITIAL_BEARER_TOKEN: ${{ vars.INITIAL_BEARER_TOKEN }}
envkey_INITIAL_GOOGLE_CREDENTIALS: ${{ vars.INITIAL_GOOGLE_CREDENTIALS }}
envkey_MAKEFILE_OVERWRITE_DOCKERNAME: ${{ vars.MAKEFILE_OVERWRITE_DOCKERNAME }}
sort_keys: false
file_name: .env.local
Expand Down Expand Up @@ -105,7 +102,6 @@ jobs:
rm ${{env.DOCKER_IMAGE_NAME}}.tar
rm Makefile
cd ..
# We're keeping the folder, because of the shared files
rmdir ${{env.FOLDER_NAME}}
- name: Print end of script message
Expand Down
109 changes: 109 additions & 0 deletions .github/workflows/testnet-workflow.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
name: Testnet

on:
push:
branches:
- testnet

workflow_dispatch:
inputs:
reason:
description: 'Reason for manual trigger'
required: false
default: 'Manual build and deploy'

jobs:
cloud_build-local_docker:
runs-on: ubuntu-latest
if: github.ref != 'refs/heads/dev'

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

- name: Make production envfile
uses: SpicyPizza/create-envfile@v2.0
with:
envkey_PORT: ${{ vars.ENVKEY_PORT }}
envkey_INITIAL_BEARER_TOKEN: ${{ vars.INITIAL_BEARER_TOKEN }}
envkey_MAKEFILE_OVERWRITE_DOCKERNAME: ${{ vars.MAKEFILE_OVERWRITE_DOCKERNAME }}
sort_keys: false
file_name: .env.local

- name: Set environment variable
run: echo "CI=false" >> $GITHUB_ENV

- name: Check version
run: make version

- name: Build the docker image
run: make composebuild-prod

- name: Display image_id variable
run: make print_image_id

- name: Compress the image.tar
run: make save_image_as_tar

- name: Set Docker image name & PORT number
run: |
export FOLDER_NAME=$(make echo_foldername)
echo "FOLDER_NAME=$FOLDER_NAME" >> $GITHUB_ENV
export DOCKER_IMAGE_NAME=$(make echo_docker_image_name)
echo "DOCKER_IMAGE_NAME=$DOCKER_IMAGE_NAME" >> $GITHUB_ENV
export APPLICATION_PORT=$(grep '^PORT=' .env.local | cut -d= -f2 | tr -d '\n')
echo "APPLICATION_PORT=$APPLICATION_PORT" >> $GITHUB_ENV
- name: Check files
run: ls -a

- name: SCP file to server
uses: appleboy/scp-action@v0.1.4
with:
host: ${{ secrets.REMOTE_HOST_TESTNET }}
username: ${{ secrets.REMOTE_USERNAME }}
key: ${{ secrets.SSH_PRIVATE_KEY }}
port: ${{ secrets.REMOTE_PORT }}
source: "${{ env.DOCKER_IMAGE_NAME }}.tar.gz,Makefile"
target: ./${{ env.FOLDER_NAME }}/ # Target is based on the host:username login path. Will create non-existant folders.

- name: Setup SSH and deploy
uses: appleboy/ssh-action@v1.0.0
with:
host: ${{secrets.REMOTE_HOST_TESTNET}}
username: ${{secrets.REMOTE_USERNAME}}
key: ${{ secrets.SSH_PRIVATE_KEY }}
port: ${{ secrets.REMOTE_PORT }}
script: |
cd ${{ env.FOLDER_NAME }}
ls
#
# Prepare stop & delete
# Docker
make stop_matching_containers
make delete_matching_images
#
# Dockerfile
if command -v pigz &> /dev/null
then
unpigz -f "${{ env.DOCKER_IMAGE_NAME }}.tar.gz"
else
gunzip -f "${{ env.DOCKER_IMAGE_NAME }}.tar.gz"
fi
#
# Load Docker
#
docker load -i ${{env.DOCKER_IMAGE_NAME}}.tar
make print_image_id
make run_container PORT=${{ env.APPLICATION_PORT }}
#
# Cleanup
#
#ls
rm ${{env.DOCKER_IMAGE_NAME}}.tar
rm Makefile
cd ..
rmdir ${{env.FOLDER_NAME}}
- name: Print end of script message
run: echo "Good Morning... You have arrived at the end of the script 0.0/"

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"form-data": "^4.0.0",
"google-auth-library": "^9.14.0",
"googleapis": "^140.0.1",
"mongodb": "^6.9.0",
"open": "^10.1.0",
"whatwg-url": "^14.0.0"
},
Expand Down
5 changes: 4 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import express from 'express';
import routes from './routes';
import { checkRequiredEnvVariables } from './dbcode/dbSetup';
import { checkRequiredEnvVariables, initializeDatabase } from './dbcode/dbSetup';

// Check required environment variables
checkRequiredEnvVariables();

// Initialize database connection
await initializeDatabase();

const app = express();
const PORT = 8080;

Expand Down
29 changes: 17 additions & 12 deletions src/dbcode/dbSetup.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,23 @@
// src/dbCode/dbSetup.ts
// src/dbcode/dbSetup.ts

import fs from 'fs';
import path from 'path';
import dotenv from 'dotenv';
import dbClient from '../dbcode/dbClient';
import MongoDbClient from './mongoDbClient';

const envPath = path.resolve(process.cwd(), '.env');
const envLocalPath = path.resolve(process.cwd(), '.env.local');

if (fs.existsSync(envPath)) {
dotenv.config({ path: envPath });
//console.log('.env file found and loaded');
} else if (fs.existsSync(envLocalPath)) {
dotenv.config({ path: envLocalPath });
//console.log('.env.local file found and loaded');
} else {
console.log('Neither .env nor .env.local file found.');
}

export function checkRequiredEnvVariables() {
const requiredVariables: string[] = [
// Add your required variables here
// For example: 'DATABASE_URL', 'API_KEY', etc.
];
const requiredVariables = ['MONGO_URI' ];

for (const variable of requiredVariables) {
if (!process.env[variable]) {
Expand All @@ -33,17 +29,26 @@ export function checkRequiredEnvVariables() {
console.log('All required environment variables are set.');
}

export function initializeTokens() {
const bearerToken = process.env.INITIAL_BEARER_TOKEN;
let dbClient: MongoDbClient;

export async function initializeDatabase() {
const mongoUri = process.env.MONGO_URI as string;

dbClient = new MongoDbClient(mongoUri);
await dbClient.connect();

const bearerToken = process.env.INITIAL_BEARER_TOKEN;
if (bearerToken) {
if (dbClient.getCurrentBearerTokenDB() === null) {
dbClient.setBearerTokenDB(bearerToken);
const currentToken = await dbClient.getCurrentBearerTokenDB();
if (currentToken === null) {
await dbClient.setBearerTokenDB(bearerToken);
console.log('Initial bearer token set from environment variable');
}
} else {
console.log('No initial bearer token provided in environment variables');
}
}

export { dbClient };

console.log('Database setup module loaded');
51 changes: 51 additions & 0 deletions src/dbcode/mongoDbClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// src/dbcode/mongoDbClient.ts

import { MongoClient, Db } from 'mongodb';
import { IDbClient } from '../types/dbInterfaces';

class MongoDbClient implements IDbClient {
private client: MongoClient;
private db: Db | null = null;

constructor(uri: string) {
this.client = new MongoClient(uri);
}

async connect() {
await this.client.connect();
this.db = this.client.db('yourDatabaseName');
console.log('Connected to MongoDB');
}

async setBearerTokenDB(token: string): Promise<boolean> {
if (!this.db) throw new Error('Database not connected');
const collection = this.db.collection('bearer_tokens');
const existingToken = await collection.findOne({});
if (existingToken) return false;
await collection.insertOne({ token });
return true;
}

async isValidBearerTokenDB(token: string): Promise<boolean> {
if (!this.db) throw new Error('Database not connected');
const collection = this.db.collection('bearer_tokens');
const result = await collection.findOne({ token });
return !!result;
}

async getCurrentBearerTokenDB(): Promise<string | null> {
if (!this.db) throw new Error('Database not connected');
const collection = this.db.collection('bearer_tokens');
const result = await collection.findOne({});
return result ? result.token : null;
}

async changeBearerTokenDB(currentToken: string, newToken: string): Promise<boolean> {
if (!this.db) throw new Error('Database not connected');
const collection = this.db.collection('bearer_tokens');
const result = await collection.updateOne({ token: currentToken }, { $set: { token: newToken } });
return result.modifiedCount > 0;
}
}

export default MongoDbClient;
Loading

0 comments on commit 8db8267

Please sign in to comment.