TomFrost / Jexl

Javascript Expression Language: Powerful context-based expression parser and evaluator
MIT License
573 stars 93 forks source link

Support Date Types in Jexl #49

Closed SureshUnnikrishnanFL closed 5 years ago

SureshUnnikrishnanFL commented 5 years ago

How do we use Date objects in Jexl?

TomFrost commented 5 years ago

Hi Suresh!

Date objects can be passed in the context and used the same as any other context value. For example:

jexl.evalSync('a > b', { a: new Date('2019-01-01T00:00:00Z'), b: new Date('2019-02-01T00:00:00Z') })
// false

jexl.evalSync('b > a', { a: new Date('2019-01-01T00:00:00Z'), b: new Date('2019-02-01T00:00:00Z') })
// true

If you need to manipulate date objects on a deeper level, transforms are great for that. Jexl's most important design point is that expressions be completely execution-safe with stock functionality, so it does not let you (or anyone with access to expressions that might be run, whether they're external users or a bad actor who has gained access to your database of expressions) to run member functions of objects in your context. But you can define transforms for date values and allow those to be called. For example:

jexl.addTransform('addSeconds', (input, seconds) => new Date(input.getTime() + seconds * 1000))

jexl.evalSync('a|addSeconds(30)', { a: new Date('2019-01-01T00:00:00Z') })
// 2019-01-01T00:00:30.000Z

Does this answer your question?

SureshUnnikrishnanFL commented 5 years ago

Hi Suresh!

Date objects can be passed in the context and used the same as any other context value. For example:

jexl.evalSync('a > b', { a: new Date('2019-01-01T00:00:00Z'), b: new Date('2019-02-01T00:00:00Z') })
// false

jexl.evalSync('b > a', { a: new Date('2019-01-01T00:00:00Z'), b: new Date('2019-02-01T00:00:00Z') })
// true

If you need to manipulate date objects on a deeper level, transforms are great for that. Jexl's most important design point is that expressions be completely execution-safe with stock functionality, so it does not let you (or anyone with access to expressions that might be run, whether they're external users or a bad actor who has gained access to your database of expressions) to run member functions of objects in your context. But you can define transforms for date values and allow those to be called. For example:

jexl.addTransform('addSeconds', (input, seconds) => new Date(input.getTime() + seconds * 1000))

jexl.evalSync('a|addSeconds(30)', { a: new Date('2019-01-01T00:00:00Z') })
// 2019-01-01T00:00:30.000Z

Does this answer your question?

This answers my question. Thanks for the quick response and an excellent library.