Created
March 28, 2023 07:24
-
-
Save Aervyon/7381d4e3b52fa9956910fbd62c06d6d2 to your computer and use it in GitHub Desktop.
This is the potential new way Folderr loads API endpoints by loading every version nearly at once.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// `this.app` is `Fastify`, https://fastify.io | |
// `this.logger` is a modified `pino` logger, https://github.com/pinojs/pino | |
// `Path` is a custom class currently used by Folderr. Might be abandoned in the future in favor of functional programming. | |
// this is an excerp from Folderr backend/core.ts | |
findPaths(dir: string): Array<Promise<{default: typeof Path}>> { | |
if (!require.main?.path) { | |
return []; | |
} | |
const paths: Array<Promise<{default: typeof Path}>> = []; | |
const apiitems = fs.readdirSync(dir); | |
for (const apiordir of apiitems) { | |
if (apiordir.startsWith('index')) continue; | |
if (apiordir.includes('.')) { | |
paths.push( | |
import( | |
join(dir, apiordir) | |
) as Promise<{default: typeof Path}> | |
); | |
continue; | |
} | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument | |
paths.push(...this.findPaths(join(dir, apiordir))); | |
} | |
return paths; | |
} | |
// eslint-disable-next-line @typescript-eslint/naming-convention | |
async initAPI(): Promise<void> { | |
let count = 0; | |
if (require.main?.path) { | |
const dir = fs.readdirSync(join(require.main?.path, 'Paths/API')); | |
const paths: | |
Array<{version: string, paths: Array<Promise<{default: typeof Path}>>}> = []; | |
for (const item of dir) { | |
if (!item.startsWith('V')) continue; // skip folders, they start with `V` here | |
const output = this.findPaths(join(require.main.path, `Paths/API/${item}`)); | |
paths.push({version: item, paths: output}); | |
} | |
paths.forEach(async value => { | |
const actpaths = await Promise.all(value.paths); | |
await this.app.register((instance, _options, done) => { | |
for (const pathimport of actpaths) { | |
// eslint-disable-next-line @typescript-eslint/naming-convention | |
const Endpoint = pathimport.default; | |
const endpoint = new Endpoint(this); | |
if (!endpoint.enabled) continue; | |
const {label} = endpoint; | |
this.internalInitPath(endpoint, instance); | |
this.logger.startup( | |
`Loaded ${label}` + | |
` ${value.version} with method ${endpoint.type}` | |
); | |
count++; | |
} | |
this.logger.startup(`Loaded ${count} API Paths (${value.version})`); | |
done(); | |
}, { | |
prefix: '/api/' | |
}); | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment