fastify / fastify-plugin

Plugin helper for Fastify
MIT License
198 stars 43 forks source link

Make plugin name more accessible #155

Closed mnpenner closed 2 years ago

mnpenner commented 3 years ago

Prerequisites

🚀 Feature Proposal

If I create a plugin like...

// database.ts 
const plugin: FastifyPluginAsync = async (api, options) => {
    api.decorate('db', null)
    // impl details
}

export default fp(plugin, {name:'db'})

And then I want to have another plugin that depends on that one but I don't want to hardcode the name, I can do it like this:

import dbPlugin from './database'

const plugin: FastifyPluginAsync = async (api, options) => {
    api.decorateRequest('user', null)
    // details
}

export default fp(plugin, {name:'user',dependencies:[dbPlugin.default[Symbol.for('fastify.display-name')]]})

But .default[Symbol.for('fastify.display-name')] is kind of a funky way to extract the plugin name.

Couldn't we add .pluginName directly to the the return function from fp? Or if you want to keep it a little more hidden, then can Fastify export these Symbols instead of having us reverse-engineer to find out what they are?

Motivation

Given above. Want easier access to this var. Also, TypeScript is freaking out when I try to access dbPlugin.default[Symbol.for('fastify.display-name')]]

Example

Above.

climba03003 commented 3 years ago

I think dbPlugin[Symbol.for('fastify.display-name')] should works?

It is true that TypeScript will throw error when accessing this property as the symbol property should add per package.

mnpenner commented 3 years ago

Oh.. I see what I did now. I had import * as plugin from './myplugin' instead of just import plugin from './mypluigin'. Yes, it works with or without .default.

Would be nice to at least get TS to recognize it.

I tried addinig

export const fastifyPluginName = Symbol.for('fastify.display-name')
export const fastifyPluginMeta = Symbol.for('plugin-meta')
export const fastifySkipOverride = Symbol.for('skip-override')

declare module 'fastify' {
    interface FastifyPluginAsync<Options> {
        [fastifySkipOverride]: boolean
        [fastifyPluginMeta]: Options
        [fastifyPluginName]: string
    }
}

But it doesn't seem to help.

climba03003 commented 3 years ago

I am not sure how to improve the type. symbol property is a tricky one in TypeScript.

But the first step should be export the symbol in this plugin. We can only reference the same unique symbol by a constant in TypeScript.

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.