Skip to content

Commit

Permalink
fix(convention): fix camel to snake for complex names
Browse files Browse the repository at this point in the history
  • Loading branch information
dalssoft committed May 5, 2023
1 parent 33a673a commit a1c7f4c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/convention.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
module.exports = class Convention {
camelToSnake (string) {
return string.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/^_/, '')
camelToSnake(string) {
return string
.replace(/^[A-Z]/, (match) => match.toLowerCase()) // Lowercase the first letter
.replace(/([a-z])([A-Z]+)/g, (match, p1, p2) => p1 + '_' + p2) // Add underscore between lowercase and uppercase letters
.toLowerCase(); // Convert the entire string to lowercase
}

toTableFieldName (entityField) {
toTableFieldName(entityField) {
return this.camelToSnake(entityField)
}

isScalarType (type) {
isScalarType(type) {
const scalarTypes = [Number, String, Boolean, Date, Object, Array]
return scalarTypes.includes(type)
}
Expand Down
30 changes: 30 additions & 0 deletions test/unit/convention.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,35 @@ describe('Convetion', () => {
//then
assert.deepStrictEqual(dbField, "field_name")
})

it('entity field name (ID) to database field name', () => {
//given
const entityField = "fieldID"
const convention = new Convetion()
//when
const dbField = convention.toTableFieldName(entityField)
//then
assert.deepStrictEqual(dbField, "field_id")
})

it('entity field name (Id) to database field name', () => {
//given
const entityField = "fieldId"
const convention = new Convetion()
//when
const dbField = convention.toTableFieldName(entityField)
//then
assert.deepStrictEqual(dbField, "field_id")
})

it('entity complex field name (Id) to database field name', () => {
//given
const entityField = "ThisIsAnFieldId"
const convention = new Convetion()
//when
const dbField = convention.toTableFieldName(entityField)
//then
assert.deepStrictEqual(dbField, "this_is_an_field_id")
})

})

0 comments on commit a1c7f4c

Please sign in to comment.