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

localhost to env #35

Merged
merged 4 commits into from
Feb 6, 2024
Merged
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
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
.env
.env.prod
dist
31 changes: 23 additions & 8 deletions backend/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
import dotenv from "dotenv";

dotenv.config();

export const PORT: number = parseInt(process.env.PORT || "8080", 10);
export const MONGODB_URI: string =
process.env.MONGODB_URI || "mongodb://localhost:27017/suriya";
export const API_VERSION: string = process.env.API_VERSION || "1.5.5";
export const PASSPORT_SECRET: string = "nodeauthsecret";
export const config = {
dotenv.config({});

const baseConfig = {
PORT: parseInt(process.env.PORT || "8080", 10),
API_VERSION: process.env.API_VERSION || "1.5.5",
PASSPORT_SECRET: "nodeauthsecret",
jwtSecret: "JWT Secret",
jwtSession: { session: false },
};
let envConfig;
switch (process.env.PROD_ENV) {
case "prod":
envConfig = {
MONGODB_URI: process.env.MONGODB_URI_PROD,
};
break;
default:
envConfig = {
MONGODB_URI:
process.env.MONGODB_URI || "mongodb://localhost:27017/suriya",
};
}

const config = { ...baseConfig, ...envConfig };

export default config;
5 changes: 2 additions & 3 deletions backend/src/controller/accountController.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { Request, Response } from "express";
import { UserModel } from "../models/Users";
import jwt from "jwt-simple";
import { config } from "../config";
import config from "../config";
import mongoose from "mongoose";
import { Status } from "../models/Status";
import { API_VERSION } from "../config";

export default {
login: async (req: Request, res: Response) => {
Expand Down Expand Up @@ -61,7 +60,7 @@ export default {
res.json({
message: "Status retrieved successfully",
status: { db: dbStatus },
api_version: API_VERSION,
api_version: config.API_VERSION,
user: {
username,
id: _id,
Expand Down
6 changes: 3 additions & 3 deletions backend/src/db.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import mongoose from "mongoose";
import { PORT, MONGODB_URI, API_VERSION } from "./config";
import config from "./config";
import { Status } from "./models/Status";

const connectToDB = async () => {
try {
const instance = await mongoose.connect(MONGODB_URI);
const instance = await mongoose.connect(config.MONGODB_URI);
console.log("Connected to MongoDB");

const status = new Status({ db: true, version: "1.0.0" });
const status = new Status({ db: true, version: config.API_VERSION });
await Status.createCollection();

const session = await instance.startSession();
Expand Down
8 changes: 4 additions & 4 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import express, { Request, Response } from "express";
import bodyParser from "body-parser";
import cors from "cors";
import connectToDB from "./db";
import { PORT, PASSPORT_SECRET } from "./config";
import config from "./config";
import passport from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import { UserModel } from "./models/Users";
Expand Down Expand Up @@ -31,7 +31,7 @@ app.get("/corstest", (req: Request, res: Response) => {

app.use(
session({
secret: PASSPORT_SECRET,
secret: config.PASSPORT_SECRET,
resave: false,
saveUninitialized: false,
})
Expand All @@ -48,6 +48,6 @@ app.use("/", statusRoutes);
app.use("/", linkRoutes);

//Express-Server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
app.listen(config.PORT, () => {
console.log(`Server is running on port ${config.PORT}`);
});
2 changes: 1 addition & 1 deletion backend/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
} from "passport-jwt";
import passport from "passport";
import { UserModel, User } from "../models/Users";
import { config } from "../config";
import config from "../config";

const jwtOptions: StrategyOptions = {
//Authorization: Bearer in request headers
Expand Down
2 changes: 1 addition & 1 deletion frontend/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ dist
dist-ssr
coverage
*.local

.env
/cypress/videos/
/cypress/screenshots/

Expand Down
2 changes: 1 addition & 1 deletion frontend/cypress.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { defineConfig } from 'cypress'
export default defineConfig({
e2e: {
specPattern: 'cypress/e2e/**/*.{cy,spec}.{js,jsx,ts,tsx}',
baseUrl: 'http://localhost:4000'
baseUrl: process.env.CYPRESS_BASE_URL
}
})
9 changes: 9 additions & 0 deletions frontend/cypress/cypress.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const { defineConfig } = require("cypress");

module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
// implement node event listeners here
},
},
});
5 changes: 5 additions & 0 deletions frontend/cypress/cypress/fixtures/example.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "[email protected]",
"body": "Fixtures are a great way to mock data for responses to routes"
}
25 changes: 25 additions & 0 deletions frontend/cypress/cypress/support/commands.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })
20 changes: 20 additions & 0 deletions frontend/cypress/cypress/support/e2e.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// ***********************************************************
// This example support/e2e.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************

// Import commands.js using ES2015 syntax:
import './commands'

// Alternatively you can use CommonJS syntax:
// require('./commands')
1 change: 1 addition & 0 deletions frontend/cypress/e2e/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["./**/*", "../support/**/*"],
"compilerOptions": {
"baseUrl": "./",
"isolatedModules": false,
"target": "es5",
"lib": ["es5", "dom"],
Expand Down
8 changes: 8 additions & 0 deletions frontend/env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string
// more env variables...
}

interface ImportMeta {
readonly env: ImportMetaEnv
}
10 changes: 6 additions & 4 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@
"private": true,
"scripts": {
"build": "run-p type-check build-only",
"cypress:open": "cypress open",
"cypress:run": "cypress run --e2e",
"test:unit": "vitest",
"test:e2e": "start-server-and-test preview http://localhost:4000 'cypress run --e2e'",
"test:e2e": "start-server-and-test preview 'cypress run --e2e'",
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore",
"build-only": "vite build",
"build-storybook": "storybook build",
"dev": "vite",
"dev": "vite ",
"format": "prettier --write src/",
"preview": "vite preview --host --port 4000",
"preview": "vite preview --host ",
"storybook": "storybook dev -p 6006",
"test:e2e:dev": "start-server-and-test 'vite dev --port 4000' http://localhost:4000 'cypress open --e2e'",
"test:e2e:dev": "start-server-and-test 'vite dev --host' $VITE_DEV_SERVER_URL 'cypress open --e2e'",
"type-check": "vue-tsc --noEmit -p tsconfig.vitest.json --composite false"
},
"dependencies": {
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/BasisHeader.vue
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
<script lang="ts">
import { defineComponent, ref } from 'vue'
import { userSessionStore } from '@/store/session'
import { API_URL } from '@/utils/config.ts'
import axios from 'axios'
export default defineComponent({
name: 'Header',
Expand All @@ -36,7 +37,7 @@ export default defineComponent({
methods: {
async logout() {
try {
const response = await axios.post('http://localhost:8080/logout')
const response = await axios.post(API_URL + '/logout')
this.sessionStore.logout()
} catch (error) {
console.error(error)
Expand Down
8 changes: 5 additions & 3 deletions frontend/src/components/BasisLogin.vue
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
<script lang="ts">
import { defineComponent } from 'vue'
import { userSessionStore } from '@/store/session'
import { API_URL } from '@/utils/config.ts'
import axios from 'axios'

export default defineComponent({
Expand All @@ -46,16 +47,17 @@ export default defineComponent({

data() {
return {
email: '', //'[email protected]',
password: '', //'password1234',
email: '[email protected]',
password: 'password1234',
errorMessage: ''
}
},

methods: {
async login() {
try {
const response = await axios.post('http://localhost:8080/login', {
console.log('API URL:', API_URL)
const response = await axios.post(API_URL + '/login', {
username: this.email,
password: this.password
})
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/CreateLink.vue
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<script lang="ts">
import axios from 'axios'
import { defineComponent } from 'vue'

import { API_URL } from '@/utils/config.ts'
interface Data {
url: string
success: boolean
Expand Down Expand Up @@ -57,7 +57,7 @@ export default defineComponent({
return
}
const payload = { url: this.url, path: this.path }
const response = await axios.post('http://localhost:8080/link', payload)
const response = await axios.post(API_URL + '/link', payload)

if (!response) {
throw new Error('Network response was not ok')
Expand Down
5 changes: 3 additions & 2 deletions frontend/src/components/EditLink.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<script lang="ts">
import axios from 'axios'
import { defineComponent } from 'vue'
import { API_URL } from '@/utils/config'

interface Data {
url: string
Expand Down Expand Up @@ -57,7 +58,7 @@ export default defineComponent({
async loadLinkData() {
console.log(`Loading data for ID: ${this.id}`)
try {
const response = await axios.get(`http://localhost:8080/link/${this.id}`)
const response = await axios.get(API_URL + `/link/${this.id}`)
console.log(response)
if (response.data) {
this.url = response.data.url
Expand All @@ -79,7 +80,7 @@ export default defineComponent({
path: this.path
}
try {
const response = await axios.put(`http://localhost:8080/link/${this.id}`, payload)
const response = await axios.put(API_URL + `/link/${this.id}`, payload)

if (response && response.data) {
alert('Link updated succesfully')
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/components/LinkList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
<script lang="ts">
import { defineComponent, type PropType } from 'vue'
import axios from 'axios'

import { API_URL } from '@/utils/config.ts'
interface LinkRow {
_id: string
url: string
Expand Down Expand Up @@ -125,7 +125,7 @@ export default defineComponent({
async fetchLinks() {
console.log('Stored token:', localStorage.getItem('access_token'))
try {
const response = await axios.get('http://localhost:8080/link')
const response = await axios.get(API_URL + '/link')

console.log('Response data:', response.data)
this.rows = response.data.sort(
Expand All @@ -138,7 +138,7 @@ export default defineComponent({
async deleteRow(rowToDelete: LinkRow) {
if (confirm('Are you sure you want to delete this link?'))
try {
const response = await axios.delete(`http://localhost:8080/link/${rowToDelete._id}`)
const response = await axios.delete(API_URL + `/link/${rowToDelete._id}`)
console.log(this.rows)
if (response.status === 200) {
this.rows = this.rows.filter((row) => row._id !== rowToDelete._id)
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/store/link.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { defineStore } from 'pinia'
import router from '@/router/index'
import axios from 'axios'

import { API_URL } from '@/utils/config'
interface LinkRow {
_id: string
url: string
Expand All @@ -27,7 +27,7 @@ export const useLinkStore = defineStore({
async fetchLinks() {
console.log('Stored token:', localStorage.getItem('access_token'))
try {
const response = await axios.get('http://localhost:8080/link')
const response = await axios.get(API_URL + '/link')

console.log('Response data:', response.data)
this.rows = response.data
Expand All @@ -39,7 +39,7 @@ export const useLinkStore = defineStore({
async deleteRow(rowToDelete: LinkRow) {
if (confirm('Are you sure you want to delete this link?'))
try {
const response = await axios.delete(`http://localhost:8080/link/${rowToDelete._id}`)
const response = await axios.delete(API_URL + `/link/${rowToDelete._id}`)
console.log(this.rows)
if (response.status === 200) {
this.rows = this.rows.filter((row) => row._id !== rowToDelete._id)
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/utils/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
const env = import.meta.env

export const API_URL = env.VITE_API_URL
1 change: 1 addition & 0 deletions frontend/src/utils/cypress.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
baseUrl: process.env.CYPRESS_BASE_URL
2 changes: 2 additions & 0 deletions frontend/test/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const env = process.env
console.log(env.USER)
Loading
Loading