Class VariableParser<Data>

Parse Variables in a String

import { string, number } from "@rjweb/utils"

type Data = {
something: number
}

const parser = new string.VariableParser<Data>()
.variable(
'round',
(args) => args
.required('number')
.optional('decimals'),
(data, args, invalid) => {
const num = parseFloat(args.number)
if (isNaN(num)) return invalid('Invalid Number')

const decimals = args.decimals ? parseInt(args.decimals) : 2
if (isNaN(decimals) || decimals > 6) return invalid('Invalid Decimal Amount')

return number.round(num * data.something, decimals).toString()
}
)
.variable(
'echo',
(args) => args
.required('text'),
(data, args) => {
return args.text
}
)
.compile()

await parser.validate('Hi', { something: 1 }) // { valid: true }
await parser.validate('Hi {{round}}', { something: 1 }) // { valid: false, error: ['Missing Required Arguments to `round`'] }
await parser.parse('I have {{round(10.32323463246, 4)}}{{echo(€\\, Sir.)}}', { something: 1 }) // 'I have 10.3232€, Sir.'

Since

1.8.3

Supports

nodejs, browser

Type Parameters

  • Data = undefined

Constructors

Properties

Methods

Constructors

Properties

variables: Record<string, {
    args: Record<string, boolean>;
    handler: ((data, args, invalid) => string | Promise<string>);
}> = {}

Type declaration

  • args: Record<string, boolean>
  • handler: ((data, args, invalid) => string | Promise<string>)
      • (data, args, invalid): string | Promise<string>
      • Parameters

        • data: Data
        • args: Record<string, undefined | string>
        • invalid: ((reason) => "")
            • (reason): ""
            • Parameters

              • reason: string

              Returns ""

        Returns string | Promise<string>

Methods

  • Compile the Parser into something usable

    Returns CompiledVariableParser<Data>

    Since

    1.8.3

  • Add a new Variable to the Parser

    Type Parameters

    • Args extends ((arg) => VariableParserArgBuilder<{}>)

    Parameters

    • name: string
    • args: Args
    • handler: ((data, args, invalid) => string | Promise<string>)
        • (data, args, invalid): string | Promise<string>
        • Parameters

          • data: Data
          • args: {
                [x in string]: ReturnType<Args> extends VariableParserArgBuilder<D>
                    ? D[x] extends true
                        ? string
                        : undefined | string
                    : never
            }
          • invalid: ((reason) => "")
              • (reason): ""
              • Parameters

                • reason: string

                Returns ""

          Returns string | Promise<string>

    Returns this

    Since

    1.8.3