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

feat: my own solution #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
172 changes: 121 additions & 51 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@
"prepare": "husky install"
},
"dependencies": {
"awilix": "^8.0.1",
"axios": "1.4.0",
"express": "^4.18.2",
"generic-interceptor": "^2.2.1",
"http-method-enum": "^1.0.0",
"http-status-codes": "^2.2.0",
"knex": "^2.5.1",
Expand Down
110 changes: 59 additions & 51 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,89 +1,97 @@
import express from "express";
import type { Express } from "express";
import http from "http";
import { appConfig } from "./shared/config";
import { v4 } from "uuid";
import { StatusCodes } from "http-status-codes";
import { UserRepository } from "./shared/users.repository";
import type { Knex } from "knex";
import knex from "knex";
import axios from "axios";
import { asClass, asValue, asFunction } from "awilix";
import { createContainer } from "awilix";
import { randomWordApiIntegration, type RandomWordApiIntegration } from "./shared/random-wort-api.integration";
import type { Route } from "./routes/items-add.get.route";
import { itemsAddGetRoute } from "./routes/items-add.get.route";
import { asArray, asProxied } from "./shared/lib/awilix.lib";
import { errorProxy } from "./shared/proxy/dependency-error-decorator.proxy";
import { statsDProxy } from "./shared/proxy/dependency-statsd.proxy";
import { loggerProxy } from "./shared/proxy/dependency-logger.proxy";
import { ItemRepository } from "./shared/items.repository";

const app = express();
const userRepository = new UserRepository();
export interface Dependencies {
userRepository: UserRepository;
itemRepository: ItemRepository;
randomWordApiIntegration: RandomWordApiIntegration;
app: Express;
database: Knex;
appConfig: typeof appConfig;
routes: Route[];
}

const database = knex({
client: "pg",
connection: {
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT),
},
acquireConnectionTimeout: 30000,
export const container = createContainer<Dependencies>().register({
userRepository: asClass(UserRepository),
itemRepository: asClass(ItemRepository),
appConfig: asValue(appConfig),
app: asValue(express()),
randomWordApiIntegration: asProxied(randomWordApiIntegration, [errorProxy, statsDProxy, loggerProxy]),
database: asFunction((dependencies: Dependencies) =>
knex({
client: "pg",
connection: {
user: dependencies.appConfig.user,
password: dependencies.appConfig.password,
database: dependencies.appConfig.database,
host: dependencies.appConfig.host,
port: dependencies.appConfig.port,
},
acquireConnectionTimeout: 30000,
}),
),
routes: asArray<Route>([itemsAddGetRoute].map((route) => asFunction(route))),
});

app.use(function (req, res, next) {
container.cradle.routes.forEach((route) => route.loadRoute());

container.cradle.app.use(function (req, res, next) {
console.log(`App received http request: ${req.method} ${req.url} | ${JSON.stringify(req.params)}`);
next();
});

app.get("/items/add/:itemName/:userId", async (req, res) => {
const itemId = v4();
const randomWordAxiosResponse = await axios({
url: "https://random-word-api.herokuapp.com/word",
});
await database.table("app.items").insert({
item_id: itemId,
user_id: req.params.userId,
item_name: req.params.itemName,
random_word: randomWordAxiosResponse.data[0],
container.cradle.app.get("/items/remove/:itemId", async (req, res) => {
await container.cradle.itemRepository.deleteOne({
itemId: req.params.itemId,
});
res.status(StatusCodes.OK).json({ itemId });
});

app.get("/items/remove/:itemId", async (req, res) => {
await database
.table("app.items")
.where({
item_id: req.params.itemId,
})
.delete();
res.sendStatus(StatusCodes.OK);
});

app.get("/items/list", async (req, res) => {
const items = await database.table("app.items").select();
container.cradle.app.get("/items/list", async (req, res) => {
const items = await container.cradle.itemRepository.listAll();
res.status(StatusCodes.OK).json({
items: items.map((item) => ({
itemId: item.item_id,
userId: item.user_id,
createdAt: item.created_at,
itemName: item.item_name,
randomWord: item.random_word,
})),
items,
});
});

app.get("/users/add/:userName", async (req, res) => {
container.cradle.app.get("/users/add/:userName", async (req, res) => {
const userId = v4();
const randomWordAxiosResponse = await axios({
url: "https://random-word-api.herokuapp.com/word",
});
await userRepository.insertOne({
await container.cradle.userRepository.insertOne({
userId,
userName: req.params.userName,
randomWord: randomWordAxiosResponse.data[0],
});
res.status(StatusCodes.OK).json({ userId });
});

app.get("/users/list", async (req, res) => {
const users = await userRepository.listAll();
container.cradle.app.get("/users/list", async (req, res) => {
const users = await container.cradle.userRepository.listAll();
res.status(StatusCodes.OK).json({ users });
});

app.get("/user-items/list/:userId", async (req, res) => {
const userItems = await database
container.cradle.app.get("/user-items/list/:userId", async (req, res) => {
const userItems = await container.cradle.database
.select("*")
.from("app.users")
.leftJoin("app.items", "users.user_id", "items.user_id")
Expand All @@ -101,12 +109,12 @@ app.get("/user-items/list/:userId", async (req, res) => {
});
});

app.use(function (req, res, next) {
container.cradle.app.use(function (req, res, next) {
console.log(`App responded on http request: <${res.statusCode}> ${req.method} ${req.url}`);
next();
});

app.use([
container.cradle.app.use([
// eslint-disable-next-line @typescript-eslint/no-unused-vars
(err, req, res, next): void => {
console.warn(err);
Expand All @@ -115,5 +123,5 @@ app.use([
]);

http
.createServer(app)
.createServer(container.cradle.app)
.listen({ port: appConfig.PORT }, () => console.log(`Server is listening on port: ${appConfig.PORT}`));
22 changes: 22 additions & 0 deletions src/routes/items-add.get.route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { StatusCodes } from "http-status-codes";
import type { Dependencies } from "..";
import { v4 } from "uuid";

export interface Route {
loadRoute: () => void;
}

export const itemsAddGetRoute = (dependencies: Dependencies): Route => ({
loadRoute: () =>
dependencies.app.get("/items/add/:itemName/:userId", async (req, res) => {
const itemId = v4();
const randomWord = await dependencies.randomWordApiIntegration.getRandomWord();
await dependencies.itemRepository.insertOne({
itemId,
userId: req.params.userId,
itemName: req.params.itemName,
randomWord,
});
res.status(StatusCodes.OK).json({ itemId });
}),
});
10 changes: 10 additions & 0 deletions src/shared/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,20 @@ const appConfigValidation = zod
.object({
NODE_STAGE: zod.string(),
PORT: zod.number({ coerce: true }),
user: zod.string(),
password: zod.string(),
database: zod.string(),
host: zod.string(),
port: zod.number({ coerce: true }),
})
.safeParse({
NODE_STAGE: process.env.NODE_STAGE,
PORT: process.env.PORT,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
host: process.env.DATABASE_HOST,
port: process.env.DATABASE_PORT,
});

if (appConfigValidation.success === false) {
Expand Down
34 changes: 34 additions & 0 deletions src/shared/items.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { Dependencies } from "..";

export class ItemRepository {
public constructor(private dependencies: Dependencies) {}

public async insertOne(payload: { itemId: string; userId: string; randomWord: string; itemName: string }) {
await this.dependencies.database.table("app.items").insert({
item_id: payload.itemId,
user_id: payload.userId,
item_name: payload.itemName,
random_word: payload.randomWord,
});
}

public async deleteOne(payload: { itemId: string }) {
await this.dependencies.database
.table("app.items")
.where({
item_id: payload.itemId,
})
.delete();
}

public async listAll() {
const items = await this.dependencies.database.table("app.items").select();
return items.map((item) => ({
itemId: item.item_id,
userId: item.user_id,
createdAt: item.created_at,
itemName: item.item_name,
randomWord: item.random_word,
}));
}
}
24 changes: 24 additions & 0 deletions src/shared/lib/awilix.lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as awilix from "awilix";
import type { BuildResolver } from "awilix";

export const asArray = <TResolver>(resolvers: awilix.Resolver<TResolver>[]): awilix.Resolver<TResolver[]> => ({
resolve: (container) => resolvers.map((resolver) => container.build(resolver)),
});
export interface DependencyProxyHandlerOptions {
dependencyName: string;
}

export const asProxied = <TFunction extends (...args: any) => any>(
fun: ((...args: any) => any) | (new (...args: any) => any),
proxies: ((options: DependencyProxyHandlerOptions) => ProxyHandler<any>)[],
): BuildResolver<ReturnType<TFunction>> =>
awilix.asFunction<ReturnType<TFunction>>(
proxies.reduce(
//@ts-ignore
(target: any, handler: TFunction) => (some: any) =>
new Proxy(target(some), handler({ dependencyName: fun.name })) as any,
fun.prototype === undefined
? fun
: (...classConstructorArgs: any): any => new (fun as new (...args: any) => any)(...classConstructorArgs),
) as any,
);
1 change: 1 addition & 0 deletions src/shared/lib/falso.lib.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * as falso from "@ngneat/falso";
Loading