Skip to content

Commit

Permalink
feat: allow for escaping periods in keys by replacing them with dashes (
Browse files Browse the repository at this point in the history
  • Loading branch information
snickbit authored Mar 11, 2024
1 parent 3a0b541 commit eeeecab
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
34 changes: 33 additions & 1 deletion packages/model/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import {Model} from '../src'

describe('Model', () => {
const instance = new Model()
let instance = new Model()
beforeEach(() => {
instance = new Model()
})

it('instance should be an instanceof Model', () => expect(instance).toBeInstanceOf(Model))
it('should have a property id', () => expect('id' in instance).toBeTruthy())
it('should have a property data', () => expect(instance.data).toBeDefined())
Expand All @@ -27,4 +31,32 @@ describe('Model', () => {
it('should have a method ensureExists()', () => expect(typeof instance.ensureExists).toBe('function'))
it('should have a method remove()', () => expect(typeof instance.remove).toBe('function'))
it('should have a method validate()', () => expect(typeof instance.validate).toBe('function'))

describe('Model.get()', () => {
it('should return the expected value from get(a)', () => {
instance.set('a', 1)
expect(instance.get('a')).toBe(1)
})

it('should return the expected value from get(a.b)', () => {
instance.set('a.b', 2)
expect(instance.get('a.b')).toBe(2)
})

it('should return the expected value from get(a.b.c)', () => {
instance.set('a.b.c', 3)
expect(instance.get('a.b.c')).toBe(3)
})

it('should replace escaped periods with dashes', () => {
instance.set('a\\.b', 4)
expect(instance.toJSON()).toEqual({'a-b': 4})
})

it('should allow for escaped periods and dashes in get', () => {
instance.set('a\\.b', 5)
expect(instance.get('a\\.b')).toBe(5)
expect(instance.get('a-b')).toBe(5)
})
})
})
7 changes: 6 additions & 1 deletion packages/model/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,12 @@ export class Model<T extends object = any, D = Partial<T>> {
this.out = new Out(`${this.options.name}#${this.is_new || !this.id ? 'new' : this.id}`)
}

protected checkKey(key): string {
protected checkKey(key: any): string {
// check for escaped periods and replace them (including the slash) with - instead
if (isString(key) && key.includes('\\.')) {
key = key.replaceAll('\\.', '-')
}

if (isString(key) && key.startsWith('.')) {
key = key.slice(1)
} else if (this.options.root) {
Expand Down

0 comments on commit eeeecab

Please sign in to comment.