Skip to content

Commit

Permalink
feat: redo first endpoint to have error codes
Browse files Browse the repository at this point in the history
  • Loading branch information
teresalves committed Jul 28, 2022
1 parent 0b6dc03 commit 0950530
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 45 deletions.
4 changes: 3 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ services:
PGUSER: teresalves
PGHOST: mydb
PGDATABASE: pipedriveDb
PGPASSWORD: example
PGPASSWORD: example
PGPORT: 5432
restart: unless-stopped
volumes:
- .:/app/
networks:
- pipedrive
depends_on:
- mydb
mydb:
container_name: "psql"
image: postgres
Expand Down
16 changes: 10 additions & 6 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
import Koa from 'koa';
import Router from 'koa-router';
import { processOrganizations } from './endpoints/organizations';
import { OrganisationInsertor } from './endpoints/organizations';
import bodyParser from 'koa-bodyparser';
import { client, connectToPg } from './postgres-setup';
import { pool } from './postgres-setup';
import { getOrganisation } from './endpoints/get-organisation';

export const app = new Koa();

const router = new Router();
app.use(bodyParser());
app.use(router.routes());
connectToPg();

router.get('/', async (ctx) => {
const client = await pool.connect();
const result = await client.query('SELECT * FROM organisations');
ctx.body = result.rows;
client.release();
});

router.post('/organisations', (ctx) => {
processOrganizations(ctx);
router.post('/organisations', async (ctx) => {
const organisationInsertor = new OrganisationInsertor();
const result = await organisationInsertor.processOrganizations(ctx);
ctx.body = result.msg;
ctx.status = result.status;
});

router.get('/organisations/:orgName', async (ctx) => {
const result = await getOrganisation(ctx);
ctx.body = result.body;
ctx.status = result.status;
});
});
115 changes: 87 additions & 28 deletions src/endpoints/organizations.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,91 @@
import { ParameterizedContext } from 'koa';
import { client } from '../postgres-setup';
import { OrganisationsBody } from './types/organisations';

export async function processOrganizations(
ctx: ParameterizedContext,
): Promise<void> {
const org: OrganisationsBody = ctx.request.body;
await recursiveOrganisationProcess(org, []);
ctx.body = 'OK';
}
import { pool } from '../postgres-setup';
import { OrganisationsBody, Result } from './types/organisations';

export class OrganisationInsertor {
operationSuccess: boolean;
errorMessage: string;
result: Result;
client;

constructor() {
this.operationSuccess = true;
this.result;
}

async processOrganizations(ctx: ParameterizedContext): Promise<Result> {
const org: OrganisationsBody = ctx.request.body;

this.result = await this.recursiveOrganisationProcess(org, []);
return this.result;
}

async function recursiveOrganisationProcess(
baseOrg: OrganisationsBody,
parents: Array<string>,
): Promise<void> {
const name = (baseOrg.org_name);
parents.push(name);
await client.query(
'INSERT INTO organisations(org_name) VALUES ($1) ON CONFLICT DO NOTHING;',
[name],
);
baseOrg.daughters?.forEach(async (daughter) => {
if (!(daughter.org_name in parents)) {
await recursiveOrganisationProcess(daughter, parents); // had to wait because we cant add the relationship before the actual daughter
await client.query(
'INSERT INTO organisations_relations(parent, daughter) VALUES ($1,$2) ON CONFLICT DO NOTHING;',
[name, (daughter.org_name)],
);
async recursiveOrganisationProcess(
baseOrg: OrganisationsBody,
parents: Array<string>,
): Promise<Result> {
if (!this.operationSuccess) return;

const client = await pool.connect();
const result = { status: 200, msg: 'OK' };
const name = baseOrg.org_name;
parents.push(name);

await client.query(
'INSERT INTO organisations(org_name) VALUES ($1) ON CONFLICT DO NOTHING;',
[name],
);
if (baseOrg.daughters) {
for (const daughter of Object.values(baseOrg.daughters)) {
await this.recursiveOrganisationProcess(daughter, parents);

try {
await client.query(
'INSERT INTO organisations_relations(parent, daughter) VALUES ($1,$2);',
[name, daughter.org_name],
);
return result;
} catch (err) {
(result.status = 400),
(result.msg = `Repeated relations: ${name} and ${daughter.org_name}`);
this.operationSuccess = false;
return result;
}
}
}
});
}

// TODO: Fix this
// async wrapInTransaction(queryText, parameters) {
// const client = await pool.connect();
// const currResult = { status: 200, msg: "OK" };
// try {
// await client.query('BEGIN')

// try {
// await client.query(queryText, parameters, function(err, res) {
// // console.log("client query result:", res);
// if(err) {
// //console.log("ERROR");
// client.query("ROLLBACK");
// // console.log("ROLLED BACK");
// // console.log(this.result);
// currResult.msg = `Inserted an already existing relation: ${parameters[0]} and ${parameters[1]}`;
// currResult.status = 400;
// this.operationSuccess = false;
// } else {
// client.query("COMMIT");
// // console.log("COMMITED");
// }
// });
// return currResult;
// } catch (err) {
// await client.query('ROLLBACK');
// console.error('Error committing transaction', err.stack);
// return currResult;
// }
// } finally {
// client.release();
// }
// }
}
5 changes: 5 additions & 0 deletions src/endpoints/types/organisations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,8 @@ export type OrganisationsBody = {
org_name: string;
daughters?: [OrganisationsBody];
};

export type Result = {
status: number;
msg: string;
};
12 changes: 2 additions & 10 deletions src/postgres-setup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Client } from 'pg';
import { Pool } from 'pg';

const clientConfig = {
host: process.env.PGHOST || 'localhost',
Expand All @@ -8,12 +8,4 @@ const clientConfig = {
database: process.env.PGDATABASE || 'pipedriveDb',
};

export const client = new Client(clientConfig);

export function connectToPg() {
client.connect().catch((error: any) => {
// console.log('error connecting')
// console.log(error);
throw error;
});
}
export const pool = new Pool(clientConfig);

0 comments on commit 0950530

Please sign in to comment.