refactor: 🚨 Make class methods that don't use this static

This commit is contained in:
Jesse Wierzbinski 2024-10-03 13:51:19 +02:00
parent 53688095cc
commit 835cdc3f18
No known key found for this signature in database
7 changed files with 47 additions and 40 deletions

View file

@ -113,7 +113,7 @@ export default apiRoute((app) =>
(error, message, app) => (error, message, app) =>
returnError( returnError(
context, context,
manager.processOAuth2Error(app), OAuthManager.processOAuth2Error(app),
error, error,
message, message,
), ),

View file

@ -104,10 +104,9 @@ export class ImageConversionPreprocessor implements MediaPreprocessor {
fileName: string, fileName: string,
newExtension: string, newExtension: string,
): string { ): string {
return this.extractFilenameFromPath(fileName).replace( return ImageConversionPreprocessor.extractFilenameFromPath(
/\.[^/.]+$/, fileName,
`.${newExtension}`, ).replace(/\.[^/.]+$/, `.${newExtension}`);
);
} }
/** /**
@ -115,7 +114,7 @@ export class ImageConversionPreprocessor implements MediaPreprocessor {
* @param path - The path to extract the filename from. * @param path - The path to extract the filename from.
* @returns The extracted filename. * @returns The extracted filename.
*/ */
private extractFilenameFromPath(path: string): string { private static extractFilenameFromPath(path: string): string {
const pathParts = path.split(/(?<!\\)\//); const pathParts = path.split(/(?<!\\)\//);
return pathParts[pathParts.length - 1]; return pathParts[pathParts.length - 1];
} }

View file

@ -56,7 +56,7 @@ describe("PluginLoader", () => {
]); ]);
// biome-ignore lint/complexity/useLiteralKeys: Private method // biome-ignore lint/complexity/useLiteralKeys: Private method
const directories = await pluginLoader["getDirectories"]("/some/path"); const directories = await PluginLoader["getDirectories"]("/some/path");
expect(directories).toEqual(["dir1", "dir2"]); expect(directories).toEqual(["dir1", "dir2"]);
}); });
@ -65,7 +65,7 @@ describe("PluginLoader", () => {
const manifestFile = const manifestFile =
// biome-ignore lint/complexity/useLiteralKeys: Private method // biome-ignore lint/complexity/useLiteralKeys: Private method
await pluginLoader["findManifestFile"]("/some/path"); await PluginLoader["findManifestFile"]("/some/path");
expect(manifestFile).toBe("manifest.json"); expect(manifestFile).toBe("manifest.json");
}); });
@ -73,7 +73,7 @@ describe("PluginLoader", () => {
mockReaddir.mockResolvedValue(["index.ts", "otherfile.txt"]); mockReaddir.mockResolvedValue(["index.ts", "otherfile.txt"]);
// biome-ignore lint/complexity/useLiteralKeys: Private method // biome-ignore lint/complexity/useLiteralKeys: Private method
const hasEntrypoint = await pluginLoader["hasEntrypoint"]("/some/path"); const hasEntrypoint = await PluginLoader["hasEntrypoint"]("/some/path");
expect(hasEntrypoint).toBe(true); expect(hasEntrypoint).toBe(true);
}); });

View file

@ -18,7 +18,7 @@ export class PluginLoader {
* @param {string} dir - The directory to search. * @param {string} dir - The directory to search.
* @returns {Promise<string[]>} - An array of directory names. * @returns {Promise<string[]>} - An array of directory names.
*/ */
private async getDirectories(dir: string): Promise<string[]> { private static async getDirectories(dir: string): Promise<string[]> {
const files = await readdir(dir, { withFileTypes: true }); const files = await readdir(dir, { withFileTypes: true });
return files.filter((f) => f.isDirectory()).map((f) => f.name); return files.filter((f) => f.isDirectory()).map((f) => f.name);
} }
@ -28,7 +28,9 @@ export class PluginLoader {
* @param {string} dir - The directory to search. * @param {string} dir - The directory to search.
* @returns {Promise<string | undefined>} - The manifest file name if found, otherwise undefined. * @returns {Promise<string | undefined>} - The manifest file name if found, otherwise undefined.
*/ */
private async findManifestFile(dir: string): Promise<string | undefined> { private static async findManifestFile(
dir: string,
): Promise<string | undefined> {
const files = await readdir(dir); const files = await readdir(dir);
return files.find((f) => f.match(/^manifest\.(json|json5|jsonc)$/)); return files.find((f) => f.match(/^manifest\.(json|json5|jsonc)$/));
} }
@ -38,7 +40,7 @@ export class PluginLoader {
* @param {string} dir - The directory to search. * @param {string} dir - The directory to search.
* @returns {Promise<boolean>} - True if the entrypoint file is found, otherwise false. * @returns {Promise<boolean>} - True if the entrypoint file is found, otherwise false.
*/ */
private async hasEntrypoint(dir: string): Promise<boolean> { private static async hasEntrypoint(dir: string): Promise<boolean> {
const files = await readdir(dir); const files = await readdir(dir);
return files.includes("index.ts") || files.includes("index.js"); return files.includes("index.ts") || files.includes("index.js");
} }
@ -79,16 +81,16 @@ export class PluginLoader {
* @returns {Promise<string[]>} - An array of plugin directories. * @returns {Promise<string[]>} - An array of plugin directories.
*/ */
public async findPlugins(dir: string): Promise<string[]> { public async findPlugins(dir: string): Promise<string[]> {
const directories = await this.getDirectories(dir); const directories = await PluginLoader.getDirectories(dir);
const plugins: string[] = []; const plugins: string[] = [];
for (const directory of directories) { for (const directory of directories) {
const manifestFile = await this.findManifestFile( const manifestFile = await PluginLoader.findManifestFile(
`${dir}/${directory}`, `${dir}/${directory}`,
); );
if ( if (
manifestFile && manifestFile &&
(await this.hasEntrypoint(`${dir}/${directory}`)) (await PluginLoader.hasEntrypoint(`${dir}/${directory}`))
) { ) {
plugins.push(directory); plugins.push(directory);
} }
@ -105,7 +107,9 @@ export class PluginLoader {
* @throws Will throw an error if the manifest file is missing or invalid. * @throws Will throw an error if the manifest file is missing or invalid.
*/ */
public async parseManifest(dir: string, plugin: string): Promise<Manifest> { public async parseManifest(dir: string, plugin: string): Promise<Manifest> {
const manifestFile = await this.findManifestFile(`${dir}/${plugin}`); const manifestFile = await PluginLoader.findManifestFile(
`${dir}/${plugin}`,
);
if (!manifestFile) { if (!manifestFile) {
throw new Error(`Plugin ${plugin} is missing a manifest file`); throw new Error(`Plugin ${plugin} is missing a manifest file`);

View file

@ -149,7 +149,7 @@ export class SonicSearchManager {
* @param n Batch number * @param n Batch number
* @param batchSize Size of the batch * @param batchSize Size of the batch
*/ */
private getNthDatabaseAccountBatch( private static getNthDatabaseAccountBatch(
n: number, n: number,
batchSize = 1000, batchSize = 1000,
): Promise<Record<string, string | Date>[]> { ): Promise<Record<string, string | Date>[]> {
@ -172,7 +172,7 @@ export class SonicSearchManager {
* @param n Batch number * @param n Batch number
* @param batchSize Size of the batch * @param batchSize Size of the batch
*/ */
private getNthDatabaseStatusBatch( private static getNthDatabaseStatusBatch(
n: number, n: number,
batchSize = 1000, batchSize = 1000,
): Promise<Record<string, string | Date>[]> { ): Promise<Record<string, string | Date>[]> {
@ -221,10 +221,11 @@ export class SonicSearchManager {
const batchCount = Math.ceil(accountCount / batchSize); const batchCount = Math.ceil(accountCount / batchSize);
for (let i = 0; i < batchCount; i++) { for (let i = 0; i < batchCount; i++) {
const accounts = await this.getNthDatabaseAccountBatch( const accounts =
i, await SonicSearchManager.getNthDatabaseAccountBatch(
batchSize, i,
); batchSize,
);
await Promise.all( await Promise.all(
accounts.map((account) => accounts.map((account) =>
this.ingestChannel.push( this.ingestChannel.push(
@ -252,7 +253,10 @@ export class SonicSearchManager {
const batchCount = Math.ceil(statusCount / batchSize); const batchCount = Math.ceil(statusCount / batchSize);
for (let i = 0; i < batchCount; i++) { for (let i = 0; i < batchCount; i++) {
const statuses = await this.getNthDatabaseStatusBatch(i, batchSize); const statuses = await SonicSearchManager.getNthDatabaseStatusBatch(
i,
batchSize,
);
await Promise.all( await Promise.all(
statuses.map((status) => statuses.map((status) =>
this.ingestChannel.push( this.ingestChannel.push(

View file

@ -33,7 +33,7 @@ export class OAuthManager {
this.issuer = found; this.issuer = found;
} }
async getFlow(flowId: string) { static async getFlow(flowId: string) {
return await db.query.OpenIdLoginFlows.findFirst({ return await db.query.OpenIdLoginFlows.findFirst({
where: (flow, { eq }) => eq(flow.id, flowId), where: (flow, { eq }) => eq(flow.id, flowId),
with: { with: {
@ -42,13 +42,13 @@ export class OAuthManager {
}); });
} }
async getAuthServer(issuerUrl: URL) { static async getAuthServer(issuerUrl: URL) {
return await discoveryRequest(issuerUrl, { return await discoveryRequest(issuerUrl, {
algorithm: "oidc", algorithm: "oidc",
}).then((res) => processDiscoveryResponse(issuerUrl, res)); }).then((res) => processDiscoveryResponse(issuerUrl, res));
} }
getParameters( static getParameters(
authServer: AuthorizationServer, authServer: AuthorizationServer,
issuer: (typeof config.oidc.providers)[0], issuer: (typeof config.oidc.providers)[0],
currentUrl: URL, currentUrl: URL,
@ -64,7 +64,7 @@ export class OAuthManager {
); );
} }
async getOIDCResponse( static async getOIDCResponse(
authServer: AuthorizationServer, authServer: AuthorizationServer,
issuer: (typeof config.oidc.providers)[0], issuer: (typeof config.oidc.providers)[0],
redirectUri: string, redirectUri: string,
@ -83,7 +83,7 @@ export class OAuthManager {
); );
} }
async processOIDCResponse( static async processOIDCResponse(
authServer: AuthorizationServer, authServer: AuthorizationServer,
issuer: (typeof config.oidc.providers)[0], issuer: (typeof config.oidc.providers)[0],
oidcResponse: Response, oidcResponse: Response,
@ -98,7 +98,7 @@ export class OAuthManager {
); );
} }
async getUserInfo( static async getUserInfo(
authServer: AuthorizationServer, authServer: AuthorizationServer,
issuer: (typeof config.oidc.providers)[0], issuer: (typeof config.oidc.providers)[0],
accessToken: string, accessToken: string,
@ -125,7 +125,7 @@ export class OAuthManager {
); );
} }
processOAuth2Error( static processOAuth2Error(
application: InferInsertModel<typeof Applications> | null, application: InferInsertModel<typeof Applications> | null,
) { ) {
return { return {
@ -212,7 +212,7 @@ export class OAuthManager {
app: Application | null, app: Application | null,
) => Response, ) => Response,
) { ) {
const flow = await this.getFlow(flowId); const flow = await OAuthManager.getFlow(flowId);
if (!flow) { if (!flow) {
return errorFn("invalid_request", "Invalid flow", null); return errorFn("invalid_request", "Invalid flow", null);
@ -220,9 +220,9 @@ export class OAuthManager {
const issuerUrl = new URL(this.issuer.url); const issuerUrl = new URL(this.issuer.url);
const authServer = await this.getAuthServer(issuerUrl); const authServer = await OAuthManager.getAuthServer(issuerUrl);
const parameters = await this.getParameters( const parameters = await OAuthManager.getParameters(
authServer, authServer,
this.issuer, this.issuer,
currentUrl, currentUrl,
@ -236,7 +236,7 @@ export class OAuthManager {
); );
} }
const oidcResponse = await this.getOIDCResponse( const oidcResponse = await OAuthManager.getOIDCResponse(
authServer, authServer,
this.issuer, this.issuer,
redirectUrl.toString(), redirectUrl.toString(),
@ -244,7 +244,7 @@ export class OAuthManager {
parameters, parameters,
); );
const result = await this.processOIDCResponse( const result = await OAuthManager.processOIDCResponse(
authServer, authServer,
this.issuer, this.issuer,
oidcResponse, oidcResponse,
@ -265,7 +265,7 @@ export class OAuthManager {
// Validate `sub` // Validate `sub`
// Later, we'll use this to automatically set the user's data // Later, we'll use this to automatically set the user's data
const userInfo = await this.getUserInfo( const userInfo = await OAuthManager.getUserInfo(
authServer, authServer,
this.issuer, this.issuer,
access_token, access_token,

View file

@ -76,7 +76,7 @@ export class Timeline<Type extends Note | User> {
switch (this.type) { switch (this.type) {
case TimelineType.Note: case TimelineType.Note:
linkHeader.push( linkHeader.push(
...(await this.fetchNoteLinkHeader( ...(await Timeline.fetchNoteLinkHeader(
objects as Note[], objects as Note[],
urlWithoutQuery, urlWithoutQuery,
limit, limit,
@ -85,7 +85,7 @@ export class Timeline<Type extends Note | User> {
break; break;
case TimelineType.User: case TimelineType.User:
linkHeader.push( linkHeader.push(
...(await this.fetchUserLinkHeader( ...(await Timeline.fetchUserLinkHeader(
objects as User[], objects as User[],
urlWithoutQuery, urlWithoutQuery,
limit, limit,
@ -98,7 +98,7 @@ export class Timeline<Type extends Note | User> {
return linkHeader.join(", "); return linkHeader.join(", ");
} }
private async fetchNoteLinkHeader( private static async fetchNoteLinkHeader(
notes: Note[], notes: Note[],
urlWithoutQuery: string, urlWithoutQuery: string,
limit: number, limit: number,
@ -126,7 +126,7 @@ export class Timeline<Type extends Note | User> {
return linkHeader; return linkHeader;
} }
private async fetchUserLinkHeader( private static async fetchUserLinkHeader(
users: User[], users: User[],
urlWithoutQuery: string, urlWithoutQuery: string,
limit: number, limit: number,