Skip to content
This repository was archived by the owner on Dec 13, 2023. It is now read-only.

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt Ramotar committed Jun 5, 2021
0 parents commit 95e1726
Show file tree
Hide file tree
Showing 19 changed files with 3,949 additions and 0 deletions.
11 changes: 11 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# /node_modules/* in the project root is ignored by default
# build artefacts
dist/*
coverage/*
# data definition files
**/*.d.ts
# 3rd party libs
/src/public/
# custom definition files
/src/types/
node_modules
21 changes: 21 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"parser": "@typescript-eslint/parser",
"extends": ["plugin:@typescript-eslint/recommended"],
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"],
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-explicit-any": 1,
"@typescript-eslint/no-inferrable-types": [
"warn",
{
"ignoreParameters": true
}
],
"@typescript-eslint/no-unused-vars": "warn"
}
}
43 changes: 43 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
lib-cov
*.seed
*.log
*.csv
*.dat
*.out
*.pid
*.gz
*.swp

pids
logs
results
tmp

# Build
public/css/main.css

# Coverage reports
coverage

# API keys and secrets
.env

# Dependency directory
node_modules/**/*
bower_components

# Editors
.idea
*.iml

# OS metadata
.DS_Store
Thumbs.db

# Ignore built ts files
build/**/*

# ignore package-lock.json
package-lock.json

src/db
6 changes: 6 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"semi": true,
"trailingComma": "none",
"singleQuote": false,
"printWidth": 120
}
13 changes: 13 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
sudo: false
language: node_js
node_js:
- 12
- 14
services:
- mongodb
cache:
directories:
- node_modules
script:
- npm run build
- npm run test
5 changes: 5 additions & 0 deletions nodemon.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"exec": "ts-node src/server.ts",
"watch": ["src"],
"ext": "ts"
}
46 changes: 46 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{
"name": "v2",
"version": "2.0.0",
"description": "Mighty Api",
"main": "build/src/server.js",
"scripts": {
"dev": "concurrently \"nodemon\" \"nodemon -x tsoa spec-and-routes\"",
"build": "tsoa spec-and-routes && tsc",
"start": "node build/src/server.js",
"prod": "npm run build && npm run start"
},
"author": "Matt Ramotar",
"license": "MIT",
"dependencies": {
"@typegoose/typegoose": "^7.6.1",
"@types/bcrypt": "^5.0.0",
"@types/body-parser": "^1.19.0",
"@types/compression": "^1.7.0",
"@types/express": "^4.17.12",
"@types/express-flash": "^0.0.2",
"@types/express-session": "^1.17.3",
"@types/graphql": "^14.5.0",
"@types/mongoose": "^5.11.97",
"@types/node": "^15.12.1",
"@types/swagger-ui-express": "^4.1.2",
"apollo-server-express": "^2.25.0",
"bcrypt": "^5.0.1",
"body-parser": "^1.19.0",
"class-validator": "^0.13.1",
"compression": "^1.7.4",
"concurrently": "^6.2.0",
"connect-mongo": "^4.4.1",
"express": "^4.17.1",
"express-flash": "^0.0.2",
"graphql": "^15.5.0",
"mongoose": "5.10.18",
"nodemon": "^2.0.7",
"reflect-metadata": "^0.1.13",
"swagger-ui-express": "^4.1.6",
"ts-node": "^10.0.0",
"tsoa": "^3.8.0",
"type-graphql": "^1.1.1",
"typescript": "^4.3.2",
"winston": "^3.3.3"
}
}
13 changes: 13 additions & 0 deletions src/api/users/controllers/UserController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Controller, Get, Path, Route, Tags } from "tsoa";
import User from "../models/User";
import UserService from "../services/UserService";

@Route("users")
@Tags("User")
export class UserController extends Controller {
/** Get user by ID */
@Get("{userId}")
async getUser(@Path() userId: string): Promise<User | null> {
return new UserService().getUser(userId);
}
}
46 changes: 46 additions & 0 deletions src/api/users/models/User.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { DocumentType, pre, prop } from "@typegoose/typegoose";
import bcrypt from "bcrypt";
import { Field, ID, ObjectType } from "type-graphql";

/**
* @tsoaModel
*/

@pre<User>("save", async function (next) {
const user = this;

if (!user.isModified("password")) return next();

const hashedPassword = await bcrypt.hash(user.password, 10);
user.password = hashedPassword;
next();
})
@ObjectType({ description: "User model" })
export default class User {
@Field(() => ID)
id!: string;

@Field()
@prop()
firstName!: string;

@Field()
@prop()
lastName!: string;

@Field()
@prop({ unique: true })
email!: string;

@Field()
@prop()
picture!: string;

@Field()
@prop()
password!: string;

public async comparePassword(this: DocumentType<User>, candidatePassword: string) {
return await bcrypt.compare(candidatePassword, this.password);
}
}
8 changes: 8 additions & 0 deletions src/api/users/services/UserService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import User from "../models/User";
import get from "./get";

export default class UserService {
public async getUser(userId: string): Promise<User | null> {
return await get(userId);
}
}
6 changes: 6 additions & 0 deletions src/api/users/services/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import User from "../models/User";
import { UserModel } from "../../../models";

export default async function getUser(userId: string): Promise<User | null> {
return await UserModel.findById(userId);
}
49 changes: 49 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import compression from "compression";
import MongoStore from "connect-mongo";
import cors from "cors";
import express, { Request as ExRequest, Response as ExResponse } from "express";
import flash from "express-flash";
import session from "express-session";
import swaggerUi from "swagger-ui-express";
import { RegisterRoutes } from "../build/routes";
import { MONGODB_URI } from "./util/secrets";

// import routes from "./routes";
// import { mightyToken } from "./middleware";

const app = express();

app.set("port", process.env.PORT || 5000);

app.use(compression());
app.use(express.json());
app.use(cors());

// app.use("/v1/*", mightyToken);

app.use((_, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});

app.use(
session({
resave: false,
saveUninitialized: false,
secret: "kelsey",
store: MongoStore.create({ mongoUrl: MONGODB_URI })
})
);

app.use("/docs", swaggerUi.serve, async (_req: ExRequest, res: ExResponse) => {
return res.send(swaggerUi.generateHTML(await import("../build/swagger.json")));
});

app.use(flash());

// app.use(routes);

RegisterRoutes(app);

export default app;
4 changes: 4 additions & 0 deletions src/models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { getModelForClass } from "@typegoose/typegoose";
import User from "./api/users/models/User";

export const UserModel = getModelForClass(User);
10 changes: 10 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import "reflect-metadata";
import app from "./app";

const main = async () => {
const port = process.env.PORT || 5000;

app.listen({ port }, () => console.log(`🚀 Server ready and listening at ==> http://localhost:${port}`));
};

main().catch((error) => console.log("🛑 Error:", error));
18 changes: 18 additions & 0 deletions src/util/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import winston from "winston";

const options: winston.LoggerOptions = {
transports: [
new winston.transports.Console({
level: process.env.NODE_ENV === "production" ? "error" : "debug"
}),
new winston.transports.File({ filename: "debug.log", level: "debug" })
]
};

const logger = winston.createLogger(options);

if (process.env.NODE_ENV !== "production") {
logger.debug("Logging initialized at debug level.");
}

export default logger;
14 changes: 14 additions & 0 deletions src/util/secrets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import logger from "./logger";
import dotenv from "dotenv";
import fs from "fs";

if (fs.existsSync(".env")) {
logger.debug("Using .env file to supply config environment variables.");
dotenv.config({ path: ".env" });
}

export const ENVIRONMENT = process.env.NODE_ENV;
export const MONGODB_URI = process.env["MONGODB_URI"];
export const KEYS = process.env.SECRET_OR_KEY;
export const SENDGRID_API_KEY = process.env.SENDGRID_API_KEY;
export const ROOT_AWS_S3 = process.env.ROOT_AWS_S3;
38 changes: 38 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"compilerOptions": {
"incremental": true,
"target": "es6",
"module": "commonjs",
"outDir": "build",

"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"noImplicitThis": true,
"alwaysStrict": true,

"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,

"moduleResolution": "node",
"baseUrl": ".",
"esModuleInterop": true,

"skipLibCheck": true,
"resolveJsonModule": true,

"experimentalDecorators": true,
"emitDecoratorMetadata": true,

"forceConsistentCasingInFileNames": true
},

"include": ["src/**/*"],

"exclude": ["node_modules"]
}
21 changes: 21 additions & 0 deletions tsoa.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"entryFile": "src/server.ts",
"noImplicitAdditionalProperties": "throw-on-extras",
"controllerPathGlobs": ["src/api/**/controllers/*Controller.ts"],
"spec": {
"specVersion": 3,
"outputDirectory": "build",
"basePath": "/v2"
},
"routes": {
"routesDir": "build",
"basePath": "/v2"
},
"compilerOptions": {
"baseUrl": ".",
"paths": {
"mongoose": ["./node_modules/mongoose"]
}
},
"ignore": ["node_modules/**/*"]
}
Loading

0 comments on commit 95e1726

Please sign in to comment.