#How to implement extension methods on utils directory

4 messages · Page 1 of 1 (latest)

edgy forge
#

I have this extension method to make a string a title case:
~/server/utils/extensions.ts

declare global {
  interface String {
    toTitleCase(): string;
  }
}

String.prototype.toTitleCase = function () {
  return this.replace(
    /\w\S*/g,

    function (s) {
      return s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
    }
  );
};

export default {};

How do I consume it into my server api? Using it seems to throws:

[nuxt] [request error] [unhandled] [500] str.toTitleCase is not a function
  ...
  at ~/.nuxt/dev/index.mjs:970:58
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async Object.handler (~/node_modules/.pnpm/h3@1.7.1/node_modules/h3/dist/index.mjs:1284:19)
  at async Server.toNodeHandle (~/node_modules/.pnpm/h3@1.7.1/node_modules/h3/dist/index.mjs:1359:7)
edgy forge
#

After futher research, it seems the prototype function declaration is not being imported :/

edgy forge
#

I wrapped the function in this function instead

export function getTitleCase(this: string): string {
  return this.replace(
    /\w\S*/g,

    function (s) {
      return s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
    }
  );
}

Then use it by using

String.prototype.toTitleCase = getTitleCase;

in my ~/server/api/ files...

#

That sucks