Skip to content

Commit

Permalink
Code Refactoring & Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
R1c4rdCo5t4 committed May 21, 2024
1 parent d3627c2 commit 7d31689
Show file tree
Hide file tree
Showing 20 changed files with 83 additions and 103 deletions.
2 changes: 1 addition & 1 deletion code/client/src/services/resource/resourceService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function resourceService(http: HttpCommunication, wid: string) {
return await http.get(`/workspaces/${wid}/${id}`);
}

async function createResource(name: string, type: ResourceType, parent: string): Promise<string> {
async function createResource(name: string, type: ResourceType, parent?: string): Promise<string> {
const resource: ResourceInputModel = { name, type, parent };
const { id } = await http.post(`/workspaces/${wid}`, resource);
return id;
Expand Down
2 changes: 1 addition & 1 deletion code/client/src/ui/contexts/workspace/useResources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function useResources() {
}

async function createResource(name: string, type: ResourceType, parent?: string) {
await service.createResource(name, type, parent || 'root');
await service.createResource(name, type, parent);
}

function onDeleteResource(id: string) {
Expand Down
3 changes: 0 additions & 3 deletions code/server/src/sql/clean_tables.sql
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
begin ;

-- Delete all rows from the resources table
delete from resource;

-- Delete all rows from the workspaces table
delete from workspace;

commit ;
18 changes: 6 additions & 12 deletions code/server/src/sql/create_tables.sql
Original file line number Diff line number Diff line change
@@ -1,30 +1,24 @@
begin;

create extension if not exists "uuid-ossp";
create extension if not exists "pgcrypto";

create type resource_type as enum ('D', 'F');

create table if not exists workspaces (
create table if not exists workspace (
id char(12) primary key default encode(gen_random_bytes(8), 'base64'),
name text not null,
created_at timestamp not null default now(),
updated_at timestamp not null default now()
);

create table if not exists resources (
create table if not exists resource (
id char(12) primary key default encode(gen_random_bytes(8), 'base64'),
workspace varchar not null references workspaces(id) on delete cascade,
workspace varchar not null references workspace(id) on delete cascade,
name text not null,
type resource_type not null,
created_at timestamp not null default now(),
updated_at timestamp not null default now()
);

create table if not exists resources_children (
parent char(12) not null references resources(id) on delete cascade,
child char(12) not null references resources(id) on delete cascade,
primary key (parent, child)
updated_at timestamp not null default now(),
children char(12)[] not null default '{}',
parent char(12) references resource(id) on delete cascade
);

commit;
10 changes: 3 additions & 7 deletions code/server/src/sql/drop_tables.sql
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
begin ;

drop table if exists resources cascade ;

drop table if exists workspaces cascade ;

drop table if exists resources_children cascade ;

drop type if exists resource_type cascade ;
drop table if exists resource cascade;
drop table if exists workspace cascade;
drop type if exists resource_type cascade;

commit ;
19 changes: 15 additions & 4 deletions code/server/src/sql/triggers/resources_triggers.sql
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
begin ;

-- Create the trigger function
create or replace function delete_resource_on_child_delete() returns trigger as $$
begin
delete from resource where id = old.child;
return old;
end;
$$ language plpgsql;

create trigger delete_resource_trigger
after delete on resource_child
for each row execute function delete_resource_on_child_delete();
-- create or replace trigger delete_resource_trigger
-- after delete on resource_child
-- for each row execute function delete_resource_on_child_delete();

create or replace function create_root_resource_on_workspace_create() returns trigger as $$
begin
insert into resource (id, name, type, parent, workspace)
values (new.id, 'root', 'F', null, new.id);
return new;
end;
$$ language plpgsql;

create or replace trigger create_root_resource_trigger
after insert on workspace
for each row execute function create_root_resource_on_workspace_create();

commit ;
3 changes: 2 additions & 1 deletion code/server/src/ts/controllers/http/handlers/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Request, Response, NextFunction } from 'express';
import { httpResponse } from '@controllers/http/utils/httpResponse';
import { ErrorLogger } from '@src/utils/logging';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export default function errorHandler(error: Error, req: Request, res: Response, next: NextFunction) {
Expand All @@ -20,5 +21,5 @@ export default function errorHandler(error: Error, req: Request, res: Response,
}
const message = response.statusCode === 500 ? 'Internal server error' : error.message;
response.send({ error: message });
//console.error(error.stack);
ErrorLogger.logError(error.message);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { Request, Response } from 'express';
import { ResourcesService } from '@services/ResourcesService';
import { InvalidParameterError } from '@domain/errors/errors';
import { Server } from 'socket.io';
import { isValidMetaOnlyValue, isValidUUID } from '@src/utils/validators';

function resourcesHandlers(service: ResourcesService, io: Server) {
/**
Expand All @@ -21,7 +20,6 @@ function resourcesHandlers(service: ResourcesService, io: Server) {
// Validate workspace id
const { wid } = req.params;
if (!wid) throw new InvalidParameterError('Workspace id is required');
if (!isValidUUID(wid)) throw new InvalidParameterError('Invalid workspace id');

// Get resource input model
const resource = req.body as ResourceInputModel;
Expand All @@ -30,7 +28,7 @@ function resourcesHandlers(service: ResourcesService, io: Server) {
if (!type) throw new InvalidParameterError('Resource type is required');

const id = await service.createResource(wid, name, type, parent);
const createdResource: WorkspaceResourceMetadata = { id, ...resource, children: [] };
const createdResource: WorkspaceResourceMetadata = { id, ...resource, children: [], parent: parent || wid };
io.in(wid).emit('createdResource', createdResource);
httpResponse.created(res).json({ id });
};
Expand All @@ -45,13 +43,9 @@ function resourcesHandlers(service: ResourcesService, io: Server) {
const { wid, id } = req.params;
if (!wid) throw new InvalidParameterError('Workspace id is required');
if (!id) throw new InvalidParameterError('Resource id is required');
if (!isValidUUID(wid)) throw new InvalidParameterError('Invalid workspace id');
if (!isValidUUID(id)) throw new InvalidParameterError('Invalid resource id');

// Get resource metadata query parameter
const { metaOnly } = req.query;
if (!isValidMetaOnlyValue(metaOnly as string)) throw new InvalidParameterError('Invalid metaOnly value');

const resource = await service.getResource(wid, id, metaOnly === 'true');
httpResponse.ok(res).json(resource);
};
Expand All @@ -66,8 +60,6 @@ function resourcesHandlers(service: ResourcesService, io: Server) {
const { wid, id } = req.params;
if (!wid) throw new InvalidParameterError('Workspace id is required');
if (!id) throw new InvalidParameterError('Resource id is required');
if (!isValidUUID(wid)) throw new InvalidParameterError('Invalid workspace id');
if (!isValidUUID(id)) throw new InvalidParameterError('Invalid resource id');

// Get resource input model
const resource = req.body as Partial<WorkspaceResource>;
Expand All @@ -88,8 +80,6 @@ function resourcesHandlers(service: ResourcesService, io: Server) {
const { wid, id } = req.params;
if (!wid) throw new InvalidParameterError('Workspace id is required');
if (!id) throw new InvalidParameterError('Resource id is required');
if (!isValidUUID(wid)) throw new InvalidParameterError('Invalid workspace id');
if (!isValidUUID(id)) throw new InvalidParameterError('Invalid resource id');

await service.deleteResource(id);
io.in(wid).emit('deletedResource', id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { WorkspaceInputModel, WorkspaceMetaData } from '@notespace/shared/src/wo
import { Services } from '@services/Services';
import { Server } from 'socket.io';
import { InvalidParameterError } from '@domain/errors/errors';
import { isValidMetaOnlyValue, isValidUUID } from '@src/utils/validators';

function workspacesHandlers(services: Services, io: Server) {
/**
Expand Down Expand Up @@ -35,17 +34,13 @@ function workspacesHandlers(services: Services, io: Server) {
const { wid } = req.params;
const { metaOnly } = req.query;
if (!wid) throw new InvalidParameterError('Workspace id is required');
if (!isValidUUID(wid)) throw new InvalidParameterError('Invalid workspace id');
if (!isValidMetaOnlyValue(metaOnly as string)) throw new InvalidParameterError('Invalid metaOnly value');

const workspace = await services.workspace.getWorkspace(wid, metaOnly === 'true');
httpResponse.ok(res).json(workspace);
};

const updateWorkspace = async (req: Request, res: Response) => {
const { wid } = req.params;
if (!wid) throw new InvalidParameterError('Workspace id is required');
if (!isValidUUID(wid)) throw new InvalidParameterError('Invalid workspace id');
const { name } = req.body as WorkspaceMetaData;
if (!name) throw new InvalidParameterError('Workspace name is required');

Expand All @@ -62,8 +57,6 @@ function workspacesHandlers(services: Services, io: Server) {
const deleteWorkspace = async (req: Request, res: Response) => {
const { wid } = req.params;
if (!wid) throw new InvalidParameterError('Workspace id is required');
if (!isValidUUID(wid)) throw new InvalidParameterError('Invalid workspace id');

await services.workspace.deleteWorkspace(wid);
io.emit('deletedWorkspace', wid);
httpResponse.noContent(res).send();
Expand Down
4 changes: 2 additions & 2 deletions code/server/src/ts/controllers/ws/initSocketEvents.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { SocketHandler } from '@controllers/ws/types';
import { Socket } from 'socket.io';

import { ControllersLogCaller } from '@src/utils/logging';
import { ControllersLogger } from '@src/utils/logging';

const logger = ControllersLogCaller('ws');
const logger = ControllersLogger('ws');

export default function initSocketEvents(events: Record<string, SocketHandler>) {
// const onCursorChange = events['cursorChange'];
Expand Down
16 changes: 8 additions & 8 deletions code/server/src/ts/databases/memory/Memory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const workspaces: Record<string, WorkspaceStorage> = {};
export function createWorkspace(name: string): string {
const id = uuid();
const root: WorkspaceResource = {
id: 'root',
id,
name: 'root',
workspace: id,
type: ResourceType.FOLDER,
Expand All @@ -32,7 +32,7 @@ export function getWorkspaces(): WorkspaceMetaData[] {
export function getWorkspace(id: string): Workspace {
const workspace = workspaces[id];
if (!workspace) throw new NotFoundError(`Workspace not found`);
const resources = Object.values(workspace.resources).filter(r => r.id !== 'root');
const resources = Object.values(workspace.resources).filter(r => r.id !== id); // exclude root
return { ...workspace, resources };
}

Expand All @@ -55,22 +55,22 @@ export function getResource(id: string): WorkspaceResource {
throw new NotFoundError(`Resource not found`);
}

export function createResource(wid: string, name: string, type: ResourceType, parent: string): string {
export function createResource(wid: string, name: string, type: ResourceType, parent?: string): string {
if (!workspaces[wid]) throw new NotFoundError(`Workspace not found`);
const id = uuid();
workspaces[wid].resources[id] = {
id,
name,
workspace: wid,
type,
parent,
parent: parent || wid,
children: [],
};

// update parent
const parentResource = getResource(parent);
parentResource.children.push(id);

if (parent) {
const parentResource = getResource(parent);
parentResource.children.push(id);
}
return id;
}

Expand Down
2 changes: 1 addition & 1 deletion code/server/src/ts/databases/memory/MemoryResourcesDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ResourceType, WorkspaceResource } from '@notespace/shared/src/workspace
import { memoryDB } from '@databases/memory/Memory';

export class MemoryResourcesDB implements ResourcesRepository {
async createResource(wid: string, name: string, type: ResourceType, parent: string): Promise<string> {
async createResource(wid: string, name: string, type: ResourceType, parent?: string): Promise<string> {
return memoryDB.createResource(wid, name, type, parent);
}
async getResource(id: string): Promise<WorkspaceResource> {
Expand Down
25 changes: 13 additions & 12 deletions code/server/src/ts/databases/postgres/PostgresResourcesDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,40 @@ import { isEmpty } from 'lodash';
import sql from '@databases/postgres/config';

export class PostgresResourcesDB implements ResourcesRepository {
async createResource(wid: string, name: string, type: ResourceType, parent: string): Promise<string> {
const resource = { workspace: wid, name, parent: parent || '', type };
async createResource(wid: string, name: string, type: ResourceType, parent?: string): Promise<string> {
const resource = { workspace: wid, name, parent: parent || wid, type };
console.log('resource', resource);
const results = await sql`
INSERT INTO resources ${sql(resource)}
RETURNING id
insert into resource ${sql(resource)}
returning id
`;
if (isEmpty(results)) throw new Error('Resource not created');
return results[0].id;
}

async getResource(id: string): Promise<WorkspaceResource> {
const results: WorkspaceResource[] = await sql`
SELECT * FROM resources WHERE id = ${id}
select * from resource where id = ${id}
`;
if (isEmpty(results)) throw new NotFoundError('Resource not found');
return results[0];
}

async updateResource(id: string, resource: Partial<WorkspaceResource>): Promise<void> {
const results = await sql`
UPDATE resources
SET ${sql(resource)}
WHERE id = ${id}
RETURNING id
update resource
set ${sql(resource)}
where id = ${id}
returning id
`;
if (isEmpty(results)) throw new NotFoundError('Resource not found');
}

async deleteResource(id: string) {
const results = await sql`
DELETE FROM resources
WHERE id = ${id}
RETURNING id
delete from resource
where id = ${id}
returning id
`;
if (isEmpty(results)) throw new NotFoundError('Resource not found');
}
Expand Down
Loading

0 comments on commit 7d31689

Please sign in to comment.