Skip to content

Commit

Permalink
team post authors
Browse files Browse the repository at this point in the history
  • Loading branch information
armintalaie committed Mar 9, 2024
1 parent 90eb51e commit 575d247
Show file tree
Hide file tree
Showing 11 changed files with 86 additions and 54 deletions.
2 changes: 1 addition & 1 deletion lib/team.stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class TeamStack extends cdk.Stack {

const apiResources: IApiResources = {
subresources: {
announcements: {
posts: {
endpoints: {
GET: {
id: 'getPosts',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"test": "jest",
"test:watch": "jest --watch",
"test:src": "jest --verbose ./src",
"start:local:api": "sam local start-api -t ./cdk.out/$npm_config_stack.template.json --port 8000 --container-host-interface host.docker.internal",
"start:local:api": "sam local start-api -t ./cdk.out/team-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}",
Expand Down
13 changes: 9 additions & 4 deletions resources/database/migrations/1708560752515.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,22 @@ image_link VARCHAR(255),
meta_data JSON
);

CREATE TABLE IF NOT EXISTS team_term (
term_year INT NOT NULL,
teamid INT NOT NULL,
PRIMARY KEY (term_year, teamid)
);


-- Create post table
CREATE TABLE IF NOT EXISTS post (
id INT AUTO_INCREMENT PRIMARY KEY,
teamid INT NOT NULL,
userid INT NOT NULL,
title VARCHAR(255) NOT NULL,
status ENUM('pinned', 'bookmarked', 'archived', 'default') DEFAULT 'default',
type ENUM('post', 'event', 'news', 'update','discussion', 'anouncement') DEFAULT 'announcement',
type ENUM('post', 'event', 'news', 'update','discussion', 'announcement') DEFAULT 'announcement',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
contents JSON,
FOREIGN KEY (`teamid`) REFERENCES `team` (`id`)
FOREIGN KEY (`userid`) REFERENCES `person` (`id`)
contents JSON
);
2 changes: 1 addition & 1 deletion resources/database/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import mysql, { Connection } from 'mysql2';
console.log('Connected to PlanetScale!')
dotenv.config();

const DATABASE_NAME = 'userbase';
const DATABASE_NAME = 'cosmic-dev';
const MIGRATION_PATH = './resources/database/migrations';

const setUpDatabase = async (
Expand Down
6 changes: 4 additions & 2 deletions scripts/build
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,7 @@ esbuild ./src/**/*.ts \
--entry-names=[dir]/[name]/index \
--bundle \
--platform=node \
--target=node16.14 \
--outdir=./dist/
--target=node18 \
--outdir=./dist/ \
--sourcemap=inline \

14 changes: 7 additions & 7 deletions src/posts/createPost.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { getDatabase, NewPost } from '../util/db';
import { LambdaBuilder } from '../util/middleware/middleware';
import { LambdaBuilder, LambdaInput } 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({shouldGetUser: true, db: db}))
.use(new Authorizer(db, { shouldGetUser: true }))
.build();

export async function router(
event: APIGatewayProxyEvent
event: LambdaInput
): Promise<APIResponse> {
if (!event.body) throw new Error('No body provided');

const body = JSON.parse(event.body);
const postParams = {body , userid: body.user.id} as unknown as NewPost;
console.log(event.googleAccount.id);
console.log(event.googleAccount.email);

const postParams = {...body , userid: event.googleAccount.id} as unknown as NewPost;
const newPost = await createPost(postParams);
return new SuccessResponse({
message: `post with id : ${newPost} created`,
Expand Down
26 changes: 22 additions & 4 deletions src/posts/getPosts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { LambdaBuilder } from '../util/middleware/middleware';
import { APIResponse, SuccessResponse } from '../util/middleware/response';
import { InputValidator } from '../util/middleware/inputValidator';
import { APIGatewayEvent } from 'aws-lambda';
import { S3 } from 'aws-sdk';


const db = getDatabase();

Expand All @@ -16,6 +18,13 @@ export async function router(

): Promise<APIResponse> {
const q = event.queryStringParameters;

const s3 = new S3({
accessKeyId: process.env.ACCESS_KEY,
secretAccessKey: process.env.SECRET_ACCESS_KEY
});

console.log(s3)
if (q && q.teamid) {
const team = await getPosts(Number(q.teamid));
return new SuccessResponse(team);
Expand All @@ -25,11 +34,20 @@ export async function router(
}
}
export const getPosts = async (teamid?: number) => {
const post = await db
let posts = await db
.selectFrom('post')
.selectAll()
.innerJoin('person', 'person.id', 'post.userid')
.select(['person.email', 'person.first_name', 'person.last_name', 'post.contents',
'post.status', 'post.updated_at', 'post.id', 'post.title', 'post.teamid', 'post.userid', 'post.type',
'post.created_at'
])
.$if(teamid !== undefined, (query) => query.where('teamid', '=', teamid as number))
.orderBy('updated_at desc')
.execute();
return post;
};

posts = posts.map((post: any) => {
return {...post, author: `${post.first_name} ${post.last_name}`};
});

return posts;
}
22 changes: 14 additions & 8 deletions src/teams/createTeam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ 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();

Expand All @@ -17,20 +16,27 @@ export async function router(
): Promise<APIResponse> {
if (!event.body) throw new Error('No body provided');

const body = JSON.parse(event.body) as NewTeam;
const body = JSON.parse(event.body) as NewTeam & { term_year: number}
const newTeamId = await createTeam(body);
return new SuccessResponse({
message: `team with id : ${newTeamId} created`,
});
}
export const createTeam = async (newTeam: NewTeam) => {
const param = newTeam;
param.meta_data = JSON.stringify(newTeam.meta_data);
console.log(param.meta_data);
console.log(param);
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(param)
.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;
};
16 changes: 10 additions & 6 deletions src/teams/getTeams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,21 @@ const db = getDatabase();

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

export async function router(): Promise<APIResponse> {
const teams = await getTeams();
return new SuccessResponse(teams);
}
export const getTeams = async () => {
const teams = await db
.selectFrom('team')
.selectAll()
.execute();
return teams;
const teams = await db.selectFrom('team').selectAll().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;
};
14 changes: 11 additions & 3 deletions src/util/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
} from 'kysely';
import { config } from 'dotenv';
import { PlanetScaleDialect } from 'kysely-planetscale'
import { fetch } from 'undici'
import { Link } from './types/general';
config();

Expand All @@ -25,15 +24,14 @@ export interface Database {
specialization: SpecializationTable;
standing: StandingTable;
team: TeamTable;
team_term: TeamTermTable;
post: PostTable;
}

export function getDatabase() {
console.log('getDatabase');
console.log(process.env.DATABASE_USERNAME);
const db = new Kysely<Database>({
dialect: new PlanetScaleDialect({
fetch,
host: process.env.DATABASE_HOST,
username: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD
Expand Down Expand Up @@ -117,6 +115,16 @@ export type Team = Selectable<TeamTable>;
export type NewTeam = Insertable<TeamTable>;
export type UpdateTeam = Updateable<TeamTable>;

export interface TeamTermTable {
teamid: number;
term_year: number;
}

export type TeamTerm = Selectable<TeamTermTable>;
export type NewTeamTerm = Insertable<TeamTermTable>;
export type UpdateTeamTerm = Updateable<TeamTermTable>;


export interface PostTable {
id: Generated<number>;
title: string;
Expand Down
23 changes: 6 additions & 17 deletions src/util/middleware/authorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@ export class Authorizer implements IMiddleware<IHandlerEvent, object> {
}
const googleAuth = await this.verifyUserIsLoggedIn(auth);

if (this.params.shouldGetUser) {
return this.getUser(googleAuth, this.connection);
}
console.log(googleAuth);
console.log("gwe");

return { googleAccount: googleAuth};
};
Expand All @@ -35,27 +34,17 @@ export class Authorizer implements IMiddleware<IHandlerEvent, object> {
throw new NotFoundError('User not found');
}

const user = await this.connection.selectFrom('person').where('email','=', googleAuthUser.email).executeTakeFirst();
console.log(googleAuthUser.email);
const user = await this.connection.selectFrom('person').where('email','=', googleAuthUser.email).selectAll().executeTakeFirst();

console.log("user");
if (!user) {
throw new NotFoundError('User not found');
}

return googleAuthUser;
return user;
};

getUser = async (googleAuth: GoogleAuthUser, db: Kysely<Database>) => {
const user = await db
.selectFrom('person')
.where('email', '=', googleAuth.email)
.selectAll()
.executeTakeFirst();

if (!user) {
throw new NotFoundError('User not found');
}
return { user, googleAccount: googleAuth };
};

constructor(connection: Kysely<Database>, params = { shouldGetUser: false}) {
this.params = params;
Expand Down

0 comments on commit 575d247

Please sign in to comment.