Skip to content

Commit

Permalink
Team updates (#95)
Browse files Browse the repository at this point in the history
* teams get fix, sql updates

* collection setup

* collection
  • Loading branch information
armintalaie committed Apr 12, 2024
1 parent 1ada6a7 commit 7e17192
Show file tree
Hide file tree
Showing 21 changed files with 536 additions and 63 deletions.
52 changes: 52 additions & 0 deletions lib/wiki.stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,61 @@ export class WikiStack extends LPStack {

const areaLambdaDir = 'dist/wiki/area';
const docLambdaDir = 'dist/wiki/doc';
const collectionLambdaDir = 'dist/wiki/collections';
const itemsLambdaDir = 'dist/wiki/collections/items';

const apiResources: IApiResources = {
subresources: {
collections: {
subresources: {
'{collectionid}': {
endpoints: {
GET: {
id: 'getCollection',
path: `${collectionLambdaDir}/getCollection`,
},
DELETE: {
id: 'deleteCollection',
path: `${collectionLambdaDir}/deleteCollection`,
},
PATCH: {
id: 'updateCollection',
path: `${collectionLambdaDir}/updateCollection`,
},
},
subresources: {
items: {
endpoints: {
POST: {
id: 'addItem',
path: `${itemsLambdaDir}/addItem`,
},
},
subresources: {
'{itemid}': {
endpoints: {
DELETE: {
id: 'deleteItem',
path: `${itemsLambdaDir}/removeItem`,
},
},
},
},
},
},
},
},
endpoints: {
GET: {
id: 'getCollections',
path: `${collectionLambdaDir}/getCollections`,
},
POST: {
id: 'createCollection',
path: `${collectionLambdaDir}/createCollection`,
},
},
},
doc: {
subresources: {
'{docid}': {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"start:local:api": "sam local start-api -t ./cdk.out/hub-wiki-stack.template.json --port 3003 ",
"invoke:lambda": "sam local invoke -t ./cdk.out/$npm_config_stack.template.json -e $npm_config_event ${npm_config_warm-containers=LAZY}",
"start:local:lambdas": "sam local start-lambda -t ./cdk.out/$npm_config_stack.template.json ${npm_config_port:3000} ${npm_config_warm-containers=LAZY}",
"db:up": "esbuild resources/database/setup.ts --entry-names=[dir]/[name]/index --bundle --platform=node --target=node16.14 --outdir=./dist/migrations && node ./dist/migrations/setup/index.js"
"db:up": "esbuild resources/database/setup.ts --entry-names=[dir]/[name]/index --bundle --platform=node --target=node16.14 --outdir=./dist/migrations && node ./dist/migrations/setup/index.js",
"db:reset": "esbuild resources/database/setup.ts --entry-names=[dir]/[name]/index --bundle --platform=node --target=node16.14 --outdir=./dist/migrations && node ./dist/migrations/setup/index.js --withreset"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.363.0",
Expand Down
8 changes: 1 addition & 7 deletions resources/database/migrations/1708560752.sql
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,10 @@ CREATE TABLE IF NOT EXISTS team (
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
image_link VARCHAR(255),
year INT NOT NULL,
meta_data JSON
);

CREATE TABLE IF NOT EXISTS team_term (
term_year INT NOT NULL,
teamid INT NOT NULL,
PRIMARY KEY (term_year, teamid),
FOREIGN KEY (teamid) REFERENCES team(id) ON DELETE CASCADE
);

-- Create post table
CREATE TABLE IF NOT EXISTS post (
id SERIAL PRIMARY KEY,
Expand Down
28 changes: 28 additions & 0 deletions resources/database/migrations/1710395365.sql
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,31 @@ CREATE TABLE IF NOT EXISTS document (
updatedat TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (areaid) REFERENCES area(id) ON DELETE CASCADE
);


-- Create collection table
CREATE TABLE IF NOT EXISTS collection (
id SERIAL PRIMARY KEY,
name VARCHAR(500) NOT NULL,
description VARCHAR(500),
updatedat TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create collection_item table
CREATE TABLE IF NOT EXISTS collection_item (
collectionid INT NOT NULL,
itemid INT NOT NULL,
itemtype VARCHAR(10) NOT NULL CHECK (itemtype IN ('area', 'document')),
PRIMARY KEY (collectionid, itemid, itemtype),
FOREIGN KEY (collectionid) REFERENCES collection(id) ON DELETE CASCADE
);


-- Create team_collection table
CREATE TABLE IF NOT EXISTS team_collection (
teamid INT NOT NULL,
collectionid INT NOT NULL,
PRIMARY KEY (teamid, collectionid),
FOREIGN KEY (teamid) REFERENCES team(id) ON DELETE CASCADE,
FOREIGN KEY (collectionid) REFERENCES collection(id) ON DELETE CASCADE
);
3 changes: 2 additions & 1 deletion resources/database/migrations/1711311965.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@ FROM
scope_role
INNER JOIN role ON role.label = scope_role.role_label
INNER JOIN person_role ON person_role.role_id = role.id
INNER JOIN person ON person.id = person_role.person_id;
INNER JOIN person ON person.id = person_role.person_id;

34 changes: 22 additions & 12 deletions resources/database/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ dotenv.config();

const DATABASE_NAME = process.env.DATABASE_NAME;
const MIGRATION_PATH = './resources/database/migrations';
const withResetFlagIndex = process.argv.indexOf('--withreset');
const withReset = withResetFlagIndex !== -1;

const setUpDatabase = async (
client: Client,
Expand All @@ -23,20 +25,29 @@ const setUpDatabase = async (
port: parseInt(process.env.DATABASE_PORT || '5432'),
});

await dbClient.connect();

console.log(chalk.blue('INFO: ') + 'Checking if migrations table exists');
try {
await dbClient.connect();

if (withReset) {
await initializeDatabase(dbClient);
} else {
console.log(
chalk.blue('INFO: ') +
'Migrations table already exists. Skipping initialization'
chalk.blue('INFO: ') + 'Checking if migrations table exists'
);

if (withReset) {
await initializeDatabase(dbClient);
} else {
console.log(
chalk.blue('INFO: ') +
'Migrations table already exists. Skipping initialization'
);
}
await runMigrations(dbClient);
} catch (error) {
console.error(chalk.bgRed('Error setting up database:'));
await dbClient.end();
throw error;
} finally {
await dbClient.end();
}
await runMigrations(dbClient);
await dbClient.end();
};

const initializeDatabase = async (client: Client): Promise<void> => {
Expand Down Expand Up @@ -203,7 +214,7 @@ const run = (): void => {
}
const client = new Client({ connectionString: connectionUrl });

setUpDatabase(client, true)
setUpDatabase(client, withReset)
.then(() => {
console.log(chalk.bgGreen('Database setup completed'));
})
Expand All @@ -212,7 +223,6 @@ const run = (): void => {
console.error(err.stack);
})
.finally(() => {
console.log('Closing connection');
client.end();
});
};
Expand Down
1 change: 0 additions & 1 deletion src/posts/createPost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ export async function router(event: LambdaInput): Promise<APIResponse> {
}
export const createPost = async (newPost: NewPost) => {
newPost.contents = JSON.stringify(newPost.contents);

try {
const { insertId } = await db
.insertInto('post')
Expand Down
12 changes: 2 additions & 10 deletions src/teams/createTeam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import { LambdaBuilder } from '../util/middleware/middleware';
import { APIResponse, SuccessResponse } from '../util/middleware/response';
import { InputValidator } from '../util/middleware/inputValidator';
import { APIGatewayProxyEvent } from 'aws-lambda';
import { Authorizer } from '../util/middleware/authorizer';

const db = getDatabase();

export const handler = new LambdaBuilder(router)
.use(new InputValidator())
// .use(new Authorizer())
.use(new Authorizer(db))
.build();

export async function router(
Expand All @@ -25,18 +26,9 @@ export async function router(
export const createTeam = async (newTeam: NewTeam & { term_year: number }) => {
const { term_year, ...team } = newTeam;
team.meta_data = JSON.stringify(team.meta_data);

const { insertId } = await db
.insertInto('team')
.values(team)
.executeTakeFirst();

if (!insertId) throw new Error('Failed to create team');

await db
.insertInto('team_term')
.values({ teamid: Number(insertId), term_year })
.executeTakeFirst();

return insertId;
};
4 changes: 2 additions & 2 deletions src/teams/getTeam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import {
} from '../util/middleware/response';
import { InputValidator } from '../util/middleware/inputValidator';
import { APIGatewayProxyEvent } from 'aws-lambda';

import { Authorizer } from '../util/middleware/authorizer';
const db = getDatabase();

export const handler = new LambdaBuilder(router)
.use(new InputValidator())
// .use(new Authorizer())
.use(new Authorizer(db))
.build();

export async function router(
Expand Down
42 changes: 21 additions & 21 deletions src/teams/getTeams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,25 +17,25 @@ export async function router(
const teams = await getTeams(query);
return new SuccessResponse(teams);
}
export const getTeams = async (query: any = {}) => {
const q = db.selectFrom('team').selectAll();
if (query.userid) {
q.innerJoin('team_member', 'team.id', 'team_member.teamid').where(
'team_member.userid',
'=',
query.userid
);
}
const teams = await q.execute();
const teamTerms = await db.selectFrom('team_term').selectAll().execute();
const teamsWithTerms: any[] = [];
for (const team of teams) {
const t = team as any;
t.team_terms = teamTerms
.filter((term) => term.teamid === team.id)
.map((term) => term.term_year);
teamsWithTerms.push(t);
}

return teamsWithTerms;
export const getTeams = async (filter: any) => {
return await db
.selectFrom('team')
.select([
'team.id',
'team.label',
'team.description',
'team.created_at',
'team.updated_at',
'team.image_link',
'team.meta_data',
'team.year',
'team.type',
])
.$if(filter.userid !== undefined, (query) =>
query
.innerJoin('team_member', 'team.id', 'team_member.teamid')
.where('team_member.userid', '=', filter.userid)
)
.orderBy('team.year desc')
.execute();
};
37 changes: 35 additions & 2 deletions src/util/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,21 @@ export interface Database {
specialization: ResourceTable;
standing: ResourceTable;
team: TeamTable;
team_term: TeamTermTable;
post: PostTable;
team_member: team_member;
area: AreaTable;
document: DocumentTable;
user_scopes_view: UserScopesViewTable;
collection: CollectionTable;
collection_item: CollectionItemTable;
team_collection: TeamCollectionTable;
}

export function getDatabase() {
const db = new Kysely<Database>({
dialect: new PostgresJSDialect({
postgres: postgres({
max: 20,
// max: 20,
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
Expand Down Expand Up @@ -96,6 +98,7 @@ export interface TeamTable {
meta_data: JSONColumnType<{
links: Link[];
}>;
year: number;
}

export type Team = Selectable<TeamTable>;
Expand Down Expand Up @@ -208,3 +211,33 @@ export interface UserScopesViewTable {
export type UserScopesView = Selectable<UserScopesViewTable>;
export type NewUserScopesView = Insertable<UserScopesViewTable>;
export type UpdateUserScopesView = Updateable<UserScopesViewTable>;

export interface CollectionTable {
id: Generated<number>;
name: string;
description: string;
updated_at: ColumnType<Date, string | undefined>;
}

export type Collection = Selectable<CollectionTable>;
export type NewCollection = Insertable<CollectionTable>;
export type UpdateCollection = Updateable<CollectionTable>;

export interface CollectionItemTable {
collectionid: number;
itemid: number;
itemtype: string;
}

export type CollectionItem = Selectable<CollectionItemTable>;
export type NewCollectionItem = Insertable<CollectionItemTable>;
export type UpdateCollectionItem = Updateable<CollectionItemTable>;

export interface TeamCollectionTable {
teamid: number;
collectionid: number;
}

export type TeamCollection = Selectable<TeamCollectionTable>;
export type NewTeamCollection = Insertable<TeamCollectionTable>;
export type UpdateTeamCollection = Updateable<TeamCollectionTable>;
4 changes: 2 additions & 2 deletions src/wiki/area/getArea.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { APIGatewayProxyEvent } from 'aws-lambda';
import { APIResponse, SuccessResponse } from '../../util/middleware/response';
import { Authorizer } from '../../util/middleware/authorizer';
import { InputValidator } from '../../util/middleware/inputValidator';
import { Database, getDatabase } from '../../util/db';
import { jsonArrayFrom } from 'kysely/helpers/postgres'
import { getDatabase } from '../../util/db';
import { jsonArrayFrom } from 'kysely/helpers/postgres';

const db = getDatabase();

Expand Down
4 changes: 1 addition & 3 deletions src/wiki/area/getAreas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ const db = getDatabase();
const LIMIT = 50;
const OFFSET = 0;
export const handler = new LambdaBuilder(getRequest)
// .use(new InputValidator())
.use(new Authorizer(db))
.use(new PaginationHelper({ limit: LIMIT, offset: OFFSET }))
.useAfter(new ResponseMetaTagger())
Expand All @@ -35,11 +34,10 @@ export async function getRequest(event: LambdaInput): Promise<APIResponse> {
}

export async function getAll(areaQuery: IAreaQuery) {
console.log('areaQuery:', areaQuery);
console.log('db:', await db);
const res = await db
.selectFrom('area')
.selectAll()
.where('area.parent_areaid', 'is', null)
.execute();
return res;
}
Loading

0 comments on commit 7e17192

Please sign in to comment.