request: starting plugins with certain condtion
z7pz opened this issue · 4 comments
Is there an existing issue or pull request for this?
- I have searched the existing issues and pull requests
Feature description
Now I'm using sharding for my bot, and i am using the @sapphire/plugin-api
so I'd be attached with discord.js, I don't have any way to call register before the login method on Sapphire Client because I can't to know what shard is that.
Desired solution
I don't have a good solution for now but I would guess that creating a method to start a plugin would be helpful
Alternatives considered
just seperate the api and that means i wont be able to use the plugin
Additional context
No response
my current solution:
import { ApplyOptions } from '@sapphire/decorators';
import { Listener, Plugin, SapphireClient, container, postInitialization, preLogin } from '@sapphire/framework';
import { loadListeners, loadMediaParsers, loadMiddlewares, loadRoutes, Server } from '@sapphire/plugin-api';
import { options } from '..';
import { UserRoute } from '../routes/user';
import { ServerRoute } from '../routes/server/server';
import { ClientOptions } from 'discord.js';
class Api extends Plugin {
/**
* @since 1.0.0
*/
public static [postInitialization](this: SapphireClient, options: ClientOptions): void {
this.server = new Server(options.api);
this.stores
.register(this.server.routes) //
.register(this.server.mediaParsers)
.register(this.server.middlewares);
container.stores.loadPiece({ name: 'UserRoute', piece: UserRoute, store: 'routes' });
container.stores.loadPiece({ name: 'ServerRoute', piece: ServerRoute, store: 'routes' });
loadListeners();
loadMediaParsers();
loadMiddlewares();
loadRoutes();
}
/**
* @since 1.0.0
*/
public static async [preLogin](this: SapphireClient): Promise<void> {
if (!(this.server.options.automaticallyConnect ?? true)) {
return;
}
await this.server.connect();
}
}
export const startApi = (client: SapphireClient) => {
SapphireClient.plugins.registerPostInitializationHook(Api[postInitialization], 'API-PostInitialization');
SapphireClient.plugins.registerPreLoginHook(Api[preLogin], 'API-PreLogin');
Api[postInitialization].call(client, options);
Api[preLogin].call(client);
for (let v of client.stores.values()) {
if (['middlewares', 'mediaParsers', 'routes'].includes(v.name)) {
v.loadAll();
}
}
};
@ApplyOptions<Listener.Options>({ once: false })
export class ShardReady extends Listener {
public override async run(id: number) {
if (id == 0) startApi(this.container.client);
this.container.logger.info(`[${id}] shard is ready.`);
}
}
i lost the feature of auto register for routes, middlewares and mediaParse
Why not follow the doc? https://sapphirejs.dev/docs/Guide/plugins/API/starting-on-single-cluster-or-shard
I'd say that this only applies for plugin-api and as linked by @swiizyy there is already code in place for that.
Closing because of the above