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: add staff-picker worker #3852

Merged
merged 3 commits into from
Oct 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions packages/supabase/database.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,37 @@ export interface Database {
};
Relationships: [];
};
'staff-picks': {
Row: {
created_at: string;
id: string;
picker_id: string;
score: number;
type: string;
};
Insert: {
created_at?: string;
id: string;
picker_id: string;
score?: number;
type: string;
};
Update: {
created_at?: string;
id?: string;
picker_id?: string;
score?: number;
type?: string;
};
Relationships: [
{
foreignKeyName: 'staff-picks_picker_id_fkey';
columns: ['picker_id'];
referencedRelation: 'rights';
referencedColumns: ['id'];
}
];
};
};
Views: {
[_ in never]: never;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ export default async (request: WorkerRequest) => {
const { payload } = jwt.decode(accessToken);
const hasOwned = await hasOwnedLensProfiles(payload.id, id, true);
if (!hasOwned) {
return new Response(
JSON.stringify({ success: false, error: Errors.InvalidProfileId })
);
return response({ success: false, error: Errors.InvalidProfileId });
}

const client = createSupabaseClient(request.env.SUPABASE_KEY);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ export default async (request: WorkerRequest) => {

const { payload } = jwt.decode(accessToken);
if (payload.id !== id) {
return new Response(
JSON.stringify({ success: false, error: Errors.InvalidAddress })
);
return response({ success: false, error: Errors.InvalidAddress });
}

const client = createSupabaseClient(request.env.SUPABASE_KEY);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,7 @@ export default async (request: WorkerRequest) => {

const hasOwned = await hasOwnedLensProfiles(payload.id, id, true);
if (!updateByAdmin && !hasOwned) {
return new Response(
JSON.stringify({ success: false, error: Errors.InvalidProfileId })
);
return response({ success: false, error: Errors.InvalidProfileId });
}

const client = createSupabaseClient(request.env.SUPABASE_KEY);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ export default async (request: WorkerRequest) => {
const { payload } = jwt.decode(accessToken);
const hasOwned = await hasOwnedLensProfiles(payload.id, id, true);
if (!hasOwned) {
return new Response(
JSON.stringify({ success: false, error: Errors.InvalidProfileId })
);
return response({ success: false, error: Errors.InvalidProfileId });
}

const client = createSupabaseClient(request.env.SUPABASE_KEY);
Expand Down
1 change: 1 addition & 0 deletions packages/workers/staff-picks/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
SUPABASE_KEY=""
6 changes: 6 additions & 0 deletions packages/workers/staff-picks/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module.exports = {
extends: [require.resolve('@hey/config/eslint/base.js')],
rules: {
'import/no-anonymous-default-export': 'off'
}
};
1 change: 1 addition & 0 deletions packages/workers/staff-picks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Staff Picks worker
29 changes: 29 additions & 0 deletions packages/workers/staff-picks/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "@workers/staff-picks",
"version": "0.0.0",
"private": true,
"license": "AGPL-3.0",
"scripts": {
"dev": "wrangler dev --port 8095",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --fix --ext .ts",
"prettier": "prettier --check \"**/*.{js,ts,tsx,md}\" --cache",
"prettier:fix": "prettier --write \"**/*.{js,ts,tsx,md}\" --cache",
"typecheck": "tsc --pretty",
"worker:deploy": "wrangler deploy --var RELEASE:\"$(git rev-parse HEAD)\""
},
"dependencies": {
"@hey/data": "workspace:*",
"@hey/lib": "workspace:*",
"@hey/supabase": "workspace:*",
"@tsndr/cloudflare-worker-jwt": "^2.2.2",
"itty-router": "^4.0.23",
"zod": "^3.22.2"
},
"devDependencies": {
"@cloudflare/workers-types": "^4.20230922.0",
"@hey/config": "workspace:*",
"typescript": "^5.2.2",
"wrangler": "^3.10.1"
}
}
80 changes: 80 additions & 0 deletions packages/workers/staff-picks/src/handlers/addPick.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { Errors } from '@hey/data/errors';
import hasOwnedLensProfiles from '@hey/lib/hasOwnedLensProfiles';
import response from '@hey/lib/response';
import validateLensAccount from '@hey/lib/validateLensAccount';
import createSupabaseClient from '@hey/supabase/createSupabaseClient';
import jwt from '@tsndr/cloudflare-worker-jwt';
import { number, object, string } from 'zod';

import checkIsStaffFromDb from '../helpers/checkIsStaffFromDb';
import type { WorkerRequest } from '../types';

type ExtensionRequest = {
id: string;
picker_id: string;
type: string;
score: number;
};

const validationSchema = object({
id: string(),
picker_id: string(),
type: string(),
score: number()
});

export default async (request: WorkerRequest) => {
const body = await request.json();
if (!body) {
return response({ success: false, error: Errors.NoBody });
}

const accessToken = request.headers.get('X-Access-Token');
if (!accessToken) {
return response({ success: false, error: Errors.NoAccessToken });
}

const validation = validationSchema.safeParse(body);

if (!validation.success) {
return response({ success: false, error: validation.error.issues });
}

const { id, picker_id, score, type } = body as ExtensionRequest;

try {
const isAuthenticated = await validateLensAccount(accessToken, true);
if (!isAuthenticated) {
return response({ success: false, error: Errors.InvalidAccesstoken });
}

const { payload } = jwt.decode(accessToken);
const hasOwned = await hasOwnedLensProfiles(payload.id, picker_id, true);
if (!hasOwned) {
return response({ success: false, error: Errors.InvalidProfileId });
}

const isStaffOnDb = await checkIsStaffFromDb(request, picker_id);
if (!isStaffOnDb) {
return response({ success: false, error: Errors.NotAdmin });
}

const client = createSupabaseClient(request.env.SUPABASE_KEY);

const { data, error } = await client
.from('staff-picks')
.upsert({ id, picker_id, type, score })
.eq('id', id)
.select()
.single();

if (error) {
throw error;
}

return response({ success: true, result: data });
} catch (error) {
console.error(error);
throw error;
}
};
27 changes: 27 additions & 0 deletions packages/workers/staff-picks/src/handlers/getStaffPick.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Errors } from '@hey/data/errors';
import response from '@hey/lib/response';
import createSupabaseClient from '@hey/supabase/createSupabaseClient';

import type { WorkerRequest } from '../types';

export default async (request: WorkerRequest) => {
const { id } = request.params;

if (!id) {
return response({ success: false, error: Errors.NoBody });
}

try {
const client = createSupabaseClient(request.env.SUPABASE_KEY);

const { data } = await client
.from('staff-picks')
.select('*')
.eq('id', id)
.single();

return response({ success: true, result: data });
} catch (error) {
throw error;
}
};
20 changes: 20 additions & 0 deletions packages/workers/staff-picks/src/handlers/getStaffPicks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import response from '@hey/lib/response';
import createSupabaseClient from '@hey/supabase/createSupabaseClient';

import type { WorkerRequest } from '../types';

export default async (request: WorkerRequest) => {
try {
const client = createSupabaseClient(request.env.SUPABASE_KEY);

const { data } = await client
.from('staff-picks')
.select('*')
.order('score', { ascending: false })
.limit(10);

return response({ success: true, result: data });
} catch (error) {
throw error;
}
};
71 changes: 71 additions & 0 deletions packages/workers/staff-picks/src/handlers/removePick.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { Errors } from '@hey/data/errors';
import hasOwnedLensProfiles from '@hey/lib/hasOwnedLensProfiles';
import response from '@hey/lib/response';
import validateLensAccount from '@hey/lib/validateLensAccount';
import createSupabaseClient from '@hey/supabase/createSupabaseClient';
import jwt from '@tsndr/cloudflare-worker-jwt';
import { object, string } from 'zod';

import checkIsStaffFromDb from '../helpers/checkIsStaffFromDb';
import type { WorkerRequest } from '../types';

type ExtensionRequest = {
id: string;
picker_id: string;
};

const validationSchema = object({
id: string(),
picker_id: string()
});

export default async (request: WorkerRequest) => {
const body = await request.json();
if (!body) {
return response({ success: false, error: Errors.NoBody });
}

const accessToken = request.headers.get('X-Access-Token');
if (!accessToken) {
return response({ success: false, error: Errors.NoAccessToken });
}

const validation = validationSchema.safeParse(body);

if (!validation.success) {
return response({ success: false, error: validation.error.issues });
}

const { id, picker_id } = body as ExtensionRequest;

try {
const isAuthenticated = await validateLensAccount(accessToken, true);
if (!isAuthenticated) {
return response({ success: false, error: Errors.InvalidAccesstoken });
}

const { payload } = jwt.decode(accessToken);
const hasOwned = await hasOwnedLensProfiles(payload.id, picker_id, true);
if (!hasOwned) {
return response({ success: false, error: Errors.InvalidProfileId });
}

const isStaffOnDb = await checkIsStaffFromDb(request, picker_id);
if (!isStaffOnDb) {
return response({ success: false, error: Errors.NotAdmin });
}

const client = createSupabaseClient(request.env.SUPABASE_KEY);

const { error } = await client.from('staff-picks').delete().eq('id', id);

if (error) {
throw error;
}

return response({ success: true });
} catch (error) {
console.error(error);
throw error;
}
};
16 changes: 16 additions & 0 deletions packages/workers/staff-picks/src/helpers/buildRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { Env, WorkerRequest } from '../types';

const buildRequest = (
request: Request,
env: Env,
ctx: ExecutionContext
): WorkerRequest => {
const temp: WorkerRequest = request as WorkerRequest;
temp.req = request;
temp.env = env;
temp.ctx = ctx;

return temp;
};

export default buildRequest;
29 changes: 29 additions & 0 deletions packages/workers/staff-picks/src/helpers/checkIsStaffFromDb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import createSupabaseClient from '@hey/supabase/createSupabaseClient';

import type { WorkerRequest } from '../types';

const checkIsStaffFromDb = async (
request: WorkerRequest,
profileId: string
) => {
const client = createSupabaseClient(request.env.SUPABASE_KEY);

const { data, error } = await client
.from('rights')
.select('id')
.eq('id', profileId);

console.log(data, profileId);

if (error) {
return false;
}

if (!data.length) {
return false;
}

return true;
};

export default checkIsStaffFromDb;