Skip to content

Commit

Permalink
feat: custom context
Browse files Browse the repository at this point in the history
  • Loading branch information
whilefoo committed Oct 23, 2023
1 parent 0fa5253 commit 7510a96
Show file tree
Hide file tree
Showing 60 changed files with 537 additions and 557 deletions.
24 changes: 12 additions & 12 deletions src/adapters/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createClient } from "@supabase/supabase-js";
import { BotConfig } from "../types";
import { Context } from "../types";
import { Access } from "./supabase/helpers/tables/access";
import { Label } from "./supabase/helpers/tables/label";
import { Locations } from "./supabase/helpers/tables/locations";
Expand All @@ -10,19 +10,19 @@ import { User } from "./supabase/helpers/tables/user";
import { Wallet } from "./supabase/helpers/tables/wallet";
import { Database } from "./supabase/types";

export function createAdapters(config: BotConfig) {
const client = generateSupabase(config.supabase.url, config.supabase.key);
export function createAdapters(context: Context) {
const client = generateSupabase(context.config.supabase.url, context.config.supabase.key);
return {
supabase: {
access: new Access(client),
wallet: new Wallet(client),
user: new User(client),
debit: new Settlement(client),
settlement: new Settlement(client),
label: new Label(client),
logs: new Logs(client),
locations: new Locations(client),
super: new Super(client),
access: new Access(client, context),
wallet: new Wallet(client, context),
user: new User(client, context),
debit: new Settlement(client, context),
settlement: new Settlement(client, context),
label: new Label(client, context),
logs: new Logs(client, context),
locations: new Locations(client, context),
super: new Super(client, context),
},
};
}
Expand Down
5 changes: 3 additions & 2 deletions src/adapters/supabase/helpers/tables/access.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Database } from "../../types/database";
import { GitHubNode } from "../client";
import { Super } from "./super";
import { UserRow } from "./user";
import { Context } from "../../../../types";
type AccessRow = Database["public"]["Tables"]["access"]["Row"];
type AccessInsert = Database["public"]["Tables"]["access"]["Insert"];
type UserWithAccess = (UserRow & { access: AccessRow | null })[];
Expand All @@ -18,8 +19,8 @@ type _Access = {
};

export class Access extends Super {
constructor(supabase: SupabaseClient) {
super(supabase);
constructor(supabase: SupabaseClient, context: Context) {
super(supabase, context);
}

private async _getUserWithAccess(id: number): Promise<UserWithAccess> {
Expand Down
5 changes: 3 additions & 2 deletions src/adapters/supabase/helpers/tables/label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { SupabaseClient } from "@supabase/supabase-js";
import { Repository } from "../../../../types/payload";
import { Database } from "../../types";
import { Super } from "./super";
import { Context } from "../../../../types";
type LabelRow = Database["public"]["Tables"]["labels"]["Row"];
export class Label extends Super {
constructor(supabase: SupabaseClient) {
super(supabase);
constructor(supabase: SupabaseClient, context: Context) {
super(supabase, context);
}

async saveLabelChange({
Expand Down
7 changes: 4 additions & 3 deletions src/adapters/supabase/helpers/tables/locations.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SupabaseClient } from "@supabase/supabase-js";
import { Super } from "./super";
import { Database } from "../../types/database";
import { Context } from "../../../../types";

// currently trying to save all of the location metadata of the event.
// seems that focusing on the IssueComments will provide the most value
Expand All @@ -16,8 +17,8 @@ export class Locations extends Super {
node_id: string | undefined;
node_type: string | undefined;

constructor(supabase: SupabaseClient) {
super(supabase);
constructor(supabase: SupabaseClient, context: Context) {
super(supabase, context);
}

public async getLocationsFromRepo(repositoryId: number) {
Expand Down Expand Up @@ -61,7 +62,7 @@ export class Locations extends Super {
}
`;

this.locationResponse = (await this.runtime.latestEventContext.octokit.graphql(graphQlQuery)) as LocationResponse;
this.locationResponse = (await this.context.event.octokit.graphql(graphQlQuery)) as LocationResponse;
console.trace(this.locationResponse);

this.user_id = this.locationResponse.data.node.author.id;
Expand Down
17 changes: 8 additions & 9 deletions src/adapters/supabase/helpers/tables/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
// Normally this is forbidden

import { SupabaseClient } from "@supabase/supabase-js";
import Runtime from "../../../../bindings/bot-runtime";
import { Database } from "../../types";
import { prettyLogs } from "../pretty-logs";
import { Super } from "./super";
import { execSync } from "child_process";
import { Context } from "../../../../types";

type LogFunction = (message: string, metadata?: any) => void;
type LogInsert = Database["public"]["Tables"]["logs"]["Insert"];
Expand Down Expand Up @@ -220,10 +220,9 @@ export class Logs extends Super {
});
}

constructor(supabase: SupabaseClient) {
super(supabase);
const runtime = Runtime.getState();
const logConfig = runtime.botConfig.log;
constructor(supabase: SupabaseClient, context: Context) {
super(supabase, context);
const logConfig = this.context.config.log;

this.environment = logConfig.logEnvironment;
this.retryLimit = logConfig.retryLimit;
Expand Down Expand Up @@ -362,11 +361,11 @@ export class Logs extends Super {
}

private _postComment(message: string) {
this.runtime.latestEventContext.octokit.issues
this.context.event.octokit.issues
.createComment({
owner: this.runtime.latestEventContext.issue().owner,
repo: this.runtime.latestEventContext.issue().repo,
issue_number: this.runtime.latestEventContext.issue().issue_number,
owner: this.context.event.issue().owner,
repo: this.context.event.issue().repo,
issue_number: this.context.event.issue().issue_number,
body: message,
})
// .then((x) => console.trace(x))
Expand Down
5 changes: 3 additions & 2 deletions src/adapters/supabase/helpers/tables/settlement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { GeneratedPermit } from "../../../../helpers/permit";
import { Comment, Payload } from "../../../../types/payload";
import { Database } from "../../types/database";
import { Super } from "./super";
import { Context } from "../../../../types";

type DebitInsert = Database["public"]["Tables"]["debits"]["Insert"];
type CreditInsert = Database["public"]["Tables"]["credits"]["Insert"];
Expand All @@ -26,8 +27,8 @@ type AddCreditWithPermit = {
};

export class Settlement extends Super {
constructor(supabase: SupabaseClient) {
super(supabase);
constructor(supabase: SupabaseClient, context: Context) {
super(supabase, context);
}

private async _lookupTokenId(networkId: number, address: string): Promise<number> {
Expand Down
9 changes: 6 additions & 3 deletions src/adapters/supabase/helpers/tables/super.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { SupabaseClient } from "@supabase/supabase-js";
import Runtime from "../../../../bindings/bot-runtime";
import { Context } from "../../../../types";

export class Super {
public supabase: SupabaseClient;
public runtime: Runtime; // convenience accessor
protected supabase: SupabaseClient;
protected runtime: Runtime; // convenience accessor
protected context: Context;

constructor(supabase: SupabaseClient) {
constructor(supabase: SupabaseClient, context: Context) {
this.supabase = supabase;
this.runtime = Runtime.getState();
this.context = context;
}
}
7 changes: 4 additions & 3 deletions src/adapters/supabase/helpers/tables/user.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { SupabaseClient } from "@supabase/supabase-js";
import { Database } from "../../types/database";
import { Super } from "./super";
import { Context } from "../../../../types";

export type UserRow = Database["public"]["Tables"]["users"]["Row"];
export class User extends Super {
constructor(supabase: SupabaseClient) {
super(supabase);
constructor(supabase: SupabaseClient, context: Context) {
super(supabase, context);
}

public async getUserId(username: string): Promise<number> {
const octokit = this.runtime.latestEventContext.octokit;
const octokit = this.context.event.octokit;
const { data } = await octokit.rest.users.getByUsername({ username });
return data.id;
}
Expand Down
26 changes: 16 additions & 10 deletions src/adapters/supabase/helpers/tables/wallet.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import { Context } from "probot/lib/context";
import { Context as ProbotContext } from "probot/lib/context";
import Runtime from "../../../../bindings/bot-runtime";
import { User } from "../../../../types";
import { Context, User } from "../../../../types";
import { Database } from "../../types/database";
import { Super } from "./super";
import { UserRow } from "./user";
Expand All @@ -11,23 +11,24 @@ type WalletRow = Database["public"]["Tables"]["wallets"]["Row"];
type WalletInsert = Database["public"]["Tables"]["wallets"]["Insert"];
type UserWithWallet = (UserRow & { wallets: WalletRow | null })[];

type IssueCommentPayload = Context<"issue_comment.created">["payload"] | Context<"issue_comment.edited">["payload"];
type IssueCommentPayload =
| ProbotContext<"issue_comment.created">["payload"]
| ProbotContext<"issue_comment.edited">["payload"];

export class Wallet extends Super {
constructor(supabase: SupabaseClient) {
super(supabase);
constructor(supabase: SupabaseClient, context: Context) {
super(supabase, context);
}

public async getAddress(id: number): Promise<string> {
const userWithWallet = await this._getUserWithWallet(id);
return this._validateAndGetWalletAddress(userWithWallet);
}

public async upsertWalletAddress(address: string) {
const runtime = Runtime.getState();
const eventContext = runtime.latestEventContext;
const payload = eventContext.payload as
| Context<"issue_comment.created">["payload"]
| Context<"issue_comment.edited">["payload"];
const payload = this.context.event.payload as
| ProbotContext<"issue_comment.created">["payload"]
| ProbotContext<"issue_comment.edited">["payload"];

const userData = await this._getUserData(payload);
const registeredWalletData = await this._getRegisteredWalletData(userData);
Expand Down Expand Up @@ -69,6 +70,7 @@ export class Wallet extends Super {
if (error) throw error;
return data as UserRow;
}

private async _getUserData(payload: IssueCommentPayload): Promise<UserRow> {
const user = await this._checkIfUserExists(payload.sender.id);
let userData = user;
Expand All @@ -78,6 +80,7 @@ export class Wallet extends Super {
}
return userData;
}

private async _registerNewUser(user: User, locationMetaData: LocationMetaData): Promise<UserRow> {
// Insert the location metadata into the locations table
const { data: locationData, error: locationError } = (await this.supabase
Expand All @@ -104,20 +107,23 @@ export class Wallet extends Super {

return userData as UserRow;
}

private async _checkIfWalletExists(
userData: UserRow
): Promise<{ data: WalletRow | null; error: PostgrestError | null }> {
const { data, error } = await this.supabase.from("wallets").select("*").eq("id", userData.wallet_id).single();

return { data: data as WalletRow, error };
}

private async _updateWalletId(walletId: number, userId: number) {
const { error } = await this.supabase.from("users").update({ wallet_id: walletId }).eq("id", userId);

if (error) {
throw error;
}
}

private async _getRegisteredWalletData(userData: UserRow): Promise<WalletRow> {
const walletResponse = await this._checkIfWalletExists(userData);
const walletData = walletResponse.data as WalletRow;
Expand Down
35 changes: 0 additions & 35 deletions src/bindings/bot-runtime.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import { Context } from "probot";
import { BotConfig } from "../types";
import { createAdapters } from "../adapters";
import { Logs } from "../adapters/supabase";
import { GitHubEvent } from "../types/payload";

class Runtime {
private static instance: Runtime;
private _eventContext: Context[];
private _botConfig: BotConfig;
private _adapters: ReturnType<typeof createAdapters>;
private _logger: Logs;

private constructor() {
this._eventContext = [] as Context[];
this._botConfig = {} as BotConfig;
this._adapters = {} as ReturnType<typeof createAdapters>;
this._logger = {} as Logs;
}
Expand All @@ -25,34 +18,6 @@ class Runtime {
return Runtime.instance;
}

// public eventContextByKeyPair(keyPair: { [key: string]: string }) {
// const [key, value] = Object.entries(keyPair)[0];
// return this._eventContext.find((context) => context[key] === value);
// }
public eventContextByType(name: GitHubEvent) {
return this._eventContext.find((context) => context.name === name);
}
// public eventContextById(id: string) {
// return this._eventContext.find((context) => context.id === id);
// }

public get latestEventContext() {
const latestContext = this._eventContext[this._eventContext.length - 1];
return latestContext;
}

public set latestEventContext(context: Context) {
this._eventContext.push(context);
}

public get botConfig(): BotConfig {
return this._botConfig;
}

public set botConfig(config: BotConfig) {
this._botConfig = config;
}

public get adapters(): ReturnType<typeof createAdapters> {
return this._adapters;
}
Expand Down
Loading

0 comments on commit 7510a96

Please sign in to comment.