Welcome to the Linux Foundation Forum!

Why do you use Object.assign?

I want to know why is good practice using assign, in that case, seems to me you want to clone opts, but I do not understand why not use only opts.

It's essentially shallow merging the options passed to the app.js plugin function with an empty object.

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Answers

    1. fastify.register(AutoLoad, {
    2. dir: path.join(__dirname, 'plugins'),
    3. options: opts // why not?
    4. })
    1. fastify.register(AutoLoad, {
    2. dir: path.join(__dirname, 'plugins'),
    3. options: Object.assign({}, opts)
    4. })
  • This would be a good issue to open on Fastify itself, I don't know why opts isn't passed directly.

    It could be that shallow cloning as a pattern for initializing plugins affords some protection against a certain class of bug that would arise from mutating opts objects at different layers. They could use spread {...opts} for shallow cloning as well, but this code was probably first written prior to spread support in Node.

  • Posts: 270
    edited January 2022

    I spoke with the lead maintainer of Fastify. It's because Fastify may mutate the opts object (mostly by adding internal tracking symbols), so using Object.assign avoids unexpected mutations of options objects between plugin layers.

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Categories

Upcoming Training