Skip to content

Commit

Permalink
implemented an accessser of #asEmailString() (#158)
Browse files Browse the repository at this point in the history
  • Loading branch information
bigen1925 authored Aug 31, 2022
1 parent 3f5689e commit 1ca2976
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
16 changes: 16 additions & 0 deletions lib/accessors/email-string.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict'

const asString = require('./string')

// eslint-disable-next-line no-control-regex
const EMAIL_REGEX = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021\u0023-\u005b\u005d-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\u0001-\u0008\u000b\u000c\u000e-\u001f\u0021-\u005a\u0053-\u007f]|\\[\u0001-\u0009\u000b\u000c\u000e-\u007f])+)\])$/

module.exports = function asEmailString (value) {
const strValue = asString(value)

if (!EMAIL_REGEX.test(strValue)) {
throw new Error('should be a valid email address')
}

return strValue
}
4 changes: 3 additions & 1 deletion lib/accessors/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@ module.exports = {
asString: require('./string'),

asUrlObject: require('./url-object'),
asUrlString: require('./url-string')
asUrlString: require('./url-string'),

asEmailString: require('./email-string')
}
16 changes: 16 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ describe('env-var', function () {
ARRAY_WITH_DELIMITER_PREFIX: ',value',
DASH_ARRAY: '1-2-3',
URL: 'http://google.com/',
EMAIL: 'email@example.com',
ENUM: 'VALID',
EMPTY_STRING: '',
EMPTY_STRING_WITH_WHITESPACE: ' '
Expand Down Expand Up @@ -584,6 +585,21 @@ describe('env-var', function () {
})
})

describe('#asEmailString', function () {
it('should return an email address', function () {
expect(mod.get('EMAIL').asEmailString()).to.be.a('string')
expect(mod.get('EMAIL').asEmailString()).to.equal(TEST_VARS.EMAIL)
})

it('should throw due to a bad email address', function () {
process.env.EMAIL = '.invalid@example.com'

expect(() => {
mod.get('EMAIL').asEmailString()
}).to.throw('env-var: "EMAIL" should be a valid email address')
})
})

describe('#example', () => {
let fromMod

Expand Down

0 comments on commit 1ca2976

Please sign in to comment.