Skip to content

Commit

Permalink
feat: remove context from addapters and pass it by parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
whilefoo committed Nov 19, 2023
1 parent f5a5c5c commit 40005e6
Show file tree
Hide file tree
Showing 58 changed files with 370 additions and 331 deletions.
21 changes: 10 additions & 11 deletions src/adapters/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { createClient } from "@supabase/supabase-js";
import { Context as ProbotContext } from "probot";
import { Access } from "./supabase/helpers/tables/access";
import { Label } from "./supabase/helpers/tables/label";
import { Locations } from "./supabase/helpers/tables/locations";
Expand All @@ -13,18 +12,18 @@ import { env } from "../bindings/env";

const supabaseClient = createClient<Database>(env.SUPABASE_URL, env.SUPABASE_KEY, { auth: { persistSession: false } });

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

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

private async _getUserWithAccess(id: number): Promise<UserWithAccess> {
const { data, error } = await this.supabase.from("access").select("*, users(*)").filter("id", "eq", id);

if (error) {
this.runtime.logger.error(error.message, error);
this.runtime.logger.error(null, error.message, error);
throw new Error(error.message);
}
return data;
Expand All @@ -36,7 +35,7 @@ export class Access extends Super {
public async getAccess(id: number): Promise<AccessRow | null> {
const userWithAccess = await this._getUserWithAccess(id);
if (userWithAccess[0]?.access === undefined) {
this.runtime.logger.debug("Access is undefined");
this.runtime.logger.debug(null, "Access is undefined");
return null;
}
if (userWithAccess[0]?.access === null) throw new Error("Access is null");
Expand Down
7 changes: 3 additions & 4 deletions src/adapters/supabase/helpers/tables/label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@ import { SupabaseClient } from "@supabase/supabase-js";
import { Repository } from "../../../../types/payload";
import { Database } from "../../types";
import { Super } from "./super";
import { Context as ProbotContext } from "probot";
import Runtime from "../../../../bindings/bot-runtime";

type LabelRow = Database["public"]["Tables"]["labels"]["Row"];

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

async saveLabelChange({
Expand Down Expand Up @@ -75,7 +74,7 @@ export class Label extends Super {

if (locationError) throw new Error(locationError.message);
if (!locationData) {
runtime.logger.warn("Repository location ID not found in database.");
runtime.logger.warn(null, "Repository location ID not found in database.");
return null;
}

Expand Down
10 changes: 5 additions & 5 deletions src/adapters/supabase/helpers/tables/locations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export class Locations extends Super {
node_id: string | undefined;
node_type: string | undefined;

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

public async getLocationsFromRepo(repositoryId: number) {
Expand All @@ -27,11 +27,11 @@ export class Locations extends Super {
.select("id")
.eq("repository_id", repositoryId);

if (error) throw this.runtime.logger.error("Error getting location data", new Error(error.message));
if (error) throw this.runtime.logger.error(null, "Error getting location data", new Error(error.message));
return locationData;
}

public async getLocationsMetaData(issueCommentId: string) {
public async getLocationsMetaData(context: ProbotContext, issueCommentId: string) {
const graphQlQuery = `
query {
node(id: "${issueCommentId}") {
Expand Down Expand Up @@ -62,7 +62,7 @@ export class Locations extends Super {
}
`;

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

this.user_id = this.locationResponse.data.node.author.id;
Expand Down
73 changes: 36 additions & 37 deletions src/adapters/supabase/helpers/tables/logs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { Super } from "./super";
type LogFunction = (message: string, metadata?: any) => void;
type LogInsert = Database["public"]["Tables"]["logs"]["Insert"];
type _LogParams = {
context: ProbotContext | null;
level: LogLevel;
consoleLog: LogFunction;
logMessage: string;
Expand Down Expand Up @@ -48,7 +49,7 @@ export class Logs extends Super {
private throttleCount = 0;
private retryLimit = 0; // Retries disabled by default

private _log({ level, consoleLog, logMessage, metadata, postComment, type }: _LogParams): LogReturn | null {
private _log({ context, level, consoleLog, logMessage, metadata, postComment, type }: _LogParams): LogReturn | null {
if (this._getNumericLevel(level) > this.maxLevel) return null; // filter out more verbose logs according to maxLevel set in config

// needs to generate three versions of the information.
Expand All @@ -57,21 +58,17 @@ export class Logs extends Super {
// - the comment to post on github (must include diff syntax)
// - the comment to post on the console (must be colorized)

if (metadata) {
// metadata = Logs.convertErrorsIntoObjects(metadata);
consoleLog(logMessage, metadata);
if (postComment) {
const colorizedCommentMessage = this._diffColorCommentMessage(type, logMessage);
const commentMetaData = Logs._commentMetaData(metadata, level);
this._postComment([colorizedCommentMessage, commentMetaData].join("\n"));
}
} else {
consoleLog(logMessage);
if (postComment) {
const colorizedCommentMessage = this._diffColorCommentMessage(type, logMessage);
this._postComment(colorizedCommentMessage);
}
consoleLog(logMessage, metadata || null);

if (context && postComment) {
const colorizedCommentMessage = this._diffColorCommentMessage(type, logMessage);
const commentMetaData = metadata ? Logs._commentMetaData(metadata, level) : null;
this._postComment(
context,
metadata ? [colorizedCommentMessage, commentMetaData].join("\n") : colorizedCommentMessage
);
}

const toSupabase = { log: logMessage, level, metadata } as LogInsert;

this._save(toSupabase);
Expand Down Expand Up @@ -115,9 +112,10 @@ export class Logs extends Super {

return metadata;
}
public ok(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public ok(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.VERBOSE,
consoleLog: prettyLogs.ok,
logMessage: log,
Expand All @@ -127,9 +125,10 @@ export class Logs extends Super {
});
}

public info(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public info(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.INFO,
consoleLog: prettyLogs.info,
logMessage: log,
Expand All @@ -139,9 +138,10 @@ export class Logs extends Super {
});
}

public warn(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public warn(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.WARN,
consoleLog: prettyLogs.warn,
logMessage: log,
Expand All @@ -151,9 +151,10 @@ export class Logs extends Super {
});
}

public debug(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public debug(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.DEBUG,
consoleLog: prettyLogs.debug,
logMessage: log,
Expand All @@ -163,7 +164,7 @@ export class Logs extends Super {
});
}

public error(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
public error(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
if (!metadata) {
metadata = Logs.convertErrorsIntoObjects(new Error(log));
const stack = metadata.stack as string[];
Expand All @@ -179,6 +180,7 @@ export class Logs extends Super {

metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.ERROR,
consoleLog: prettyLogs.error,
logMessage: log,
Expand All @@ -188,9 +190,10 @@ export class Logs extends Super {
});
}

http(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
http(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.HTTP,
consoleLog: prettyLogs.http,
logMessage: log,
Expand All @@ -200,9 +203,10 @@ export class Logs extends Super {
});
}

verbose(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
verbose(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.VERBOSE,
consoleLog: prettyLogs.verbose,
logMessage: log,
Expand All @@ -212,9 +216,10 @@ export class Logs extends Super {
});
}

silly(log: string, metadata?: any, postComment?: boolean): LogReturn | null {
silly(context: ProbotContext | null, log: string, metadata?: any, postComment?: boolean): LogReturn | null {
metadata = this._addDiagnosticInformation(metadata);
return this._log({
context,
level: LogLevel.SILLY,
consoleLog: prettyLogs.silly,
logMessage: log,
Expand All @@ -224,14 +229,8 @@ export class Logs extends Super {
});
}

constructor(
supabase: SupabaseClient,
context: ProbotContext,
environment: string,
retryLimit: number,
logLevel: LogLevel
) {
super(supabase, context);
constructor(supabase: SupabaseClient, environment: string, retryLimit: number, logLevel: LogLevel) {
super(supabase);

this.environment = environment;
this.retryLimit = retryLimit;
Expand Down Expand Up @@ -312,7 +311,7 @@ export class Logs extends Super {
}

static _commentMetaData(metadata: any, level: LogLevel) {
Runtime.getState().logger.debug("the main place that metadata is being serialized as an html comment");
Runtime.getState().logger.debug(null, "the main place that metadata is being serialized as an html comment");
const prettySerialized = JSON.stringify(metadata, null, 2);
// first check if metadata is an error, then post it as a json comment
// otherwise post it as an html comment
Expand Down Expand Up @@ -367,13 +366,13 @@ export class Logs extends Super {
return [diffHeader, message, diffFooter].join("\n");
}

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

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

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

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

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

constructor(supabase: SupabaseClient, context: ProbotContext) {
constructor(supabase: SupabaseClient) {
this.supabase = supabase;
this.runtime = Runtime.getState();
this.context = context;
}
}
11 changes: 5 additions & 6 deletions src/adapters/supabase/helpers/tables/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ import { Context as ProbotContext } from "probot";

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

public async getUserId(username: string): Promise<number> {
const octokit = this.context.octokit;
const { data } = await octokit.rest.users.getByUsername({ username });
public async getUserId(context: ProbotContext, username: string): Promise<number> {
const { data } = await context.octokit.rest.users.getByUsername({ username });
return data.id;
}

Expand Down Expand Up @@ -39,7 +38,7 @@ export class User extends Super {
.eq("user_id", userId)
.order("id", { ascending: false }) // get the latest one
.maybeSingle();
if (accessError) throw this.runtime.logger.error("Error getting access data", accessError);
if (accessError) throw this.runtime.logger.error(null, "Error getting access data", accessError);
return accessData;
}
}
Loading

0 comments on commit 40005e6

Please sign in to comment.