Repository: freeCodeCamp/freeCodeCamp
File: api/src/routes/settings.ts (TypeScript)

Code before:
  );

  fastify.put(
    '/update-my-about',
    {
      schema: {
        body: Type.Object({
          about: Type.Optional(Type.String()),
          name: Type.Optional(Type.String()),
          picture: Type.Optional(Type.String({ format: 'url' })),
          location: Type.Optional(Type.String())
        }),
        response: {
          200: Type.Object({
            message: Type.Literal('flash.updated-about-me'),
            type: Type.Literal('success')
          }),
          500: Type.Object({
            message: Type.Literal('flash.wrong-updating'),
            type: Type.Literal('danger')
          })
        }
      }
    },
    async (req, reply) => {
      let isURL: URL;
      if (req.body.picture) isURL = new URL(req.body.picture);
      try {
        await fastify.prisma.user.update({
          where: { id: req.session.user.id },
          data: {
            about: req.body.about,
            name: req.body.name,
            location: req.body.location,
            // how is the variable is used before assigned?
            ...(isURL && { picture: req.body.picture })
          }
        });

        return {
          message: 'flash.updated-about-me',
          type: 'success'
        } as const;
      } catch (err) {
        fastify.log.error(err);
        void reply.code(500);
        return { message: 'flash.wrong-updating', type: 'danger' } as const;
      }
    }
  );


Review comment (suggestion):
```suggestion
      let isURL: URL | null = null;
```

The variable is being used before it is assigned because it is only assigned in the `if` statement. If the condition isn't true, the variable remains unassigned when we go to check the truthiness.

Giving it a fallback value will resolve this.

However, the variable name is a bit of a misnomer - if we want to use this specifically to indicate whether there is a valid URL (as the name suggests), we should set it to a boolean and initialise it as false, instead.

Code after:
      } catch (err) {
        fastify.log.error(err);
        void reply.code(500);
        return { message: 'flash.wrong-updating', type: 'danger' } as const;
      }
    }
  );

  fastify.put(
    '/update-my-username',
    {
      schema: schemas.updateMyUsername,
      attachValidation: true
    },
    async (req, reply) => {
      try {
        const user = await fastify.prisma.user.findFirstOrThrow({
          where: { id: req.session.user.id }
        });

        const newUsernameDisplay = req.body.username.trim();
        const oldUsernameDisplay = user.usernameDisplay?.trim();

        const newUsername = newUsernameDisplay.toLowerCase();
        const oldUsername = user.username.toLowerCase();

        const usernameUnchanged =
          newUsername === oldUsername &&
          newUsernameDisplay === oldUsernameDisplay;

        if (usernameUnchanged) {
          void reply.code(400);
          return {
            message: 'flash.username-used',
            type: 'info'
          } as const;
        }

        if (req.validationError) {
          void reply.code(400);
          return {
            message: req.validationError.message,
            type: 'info'
          } as const;
        }

        const validation = isValidUsername(newUsername);

        if (!validation.valid) {
          void reply.code(400);
          return {