Skip to content

Commit

Permalink
feat: add email validation (#2431)
Browse files Browse the repository at this point in the history
  • Loading branch information
brunomiguelpinto authored Aug 19, 2024
1 parent 1e643d2 commit a6a3632
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
14 changes: 14 additions & 0 deletions app/services/customers/create_service.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ def create_from_api(organization:, params:)
new_customer = customer.new_record?
shipping_address = params[:shipping_address] ||= {}

unless valid_email?(params[:email])
return result.single_validation_failure!(
field: :email,
error_code: 'invalid_format'
)
end

unless valid_metadata_count?(metadata: params[:metadata])
return result.single_validation_failure!(
field: :metadata,
Expand Down Expand Up @@ -187,6 +194,13 @@ def create(**args)

private

def valid_email?(email)
return true if email.nil?

email_regexp = /\A[^@\s]+@[^@\s]+\z/
email_regexp.match?(email).present?
end

def valid_metadata_count?(metadata:)
return true if metadata.blank?
return true if metadata.count <= ::Metadata::CustomerMetadata::COUNT_PER_CUSTOMER
Expand Down
37 changes: 37 additions & 0 deletions spec/services/customers/create_service_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,43 @@
)
end

context 'with invalid email' do
let(:create_args) do
{
external_id:,
name: 'Foo Bar',
currency: 'EUR',
email: '@missingusername.com',
tax_identification_number: '123456789',
billing_configuration: {
document_locale: 'fr'
},
shipping_address: {
address_line1: 'line1',
address_line2: 'line2',
city: 'Paris',
zipcode: '123456',
state: 'foobar',
country: 'FR'
}
}
end

it 'fails to create customer with wrong email' do
result = customers_service.create_from_api(
organization:,
params: create_args
)

aggregate_failures do
expect(result).not_to be_success
expect(result.error).to be_a(BaseService::ValidationFailure)
expect(result.error.messages.keys).to include(:email)
expect(result.error.messages[:email]).to include('invalid_format')
end
end
end

context 'with external_id already used by a deleted customer' do
it 'creates a customer with the same external_id' do
create(:customer, :deleted, organization:, external_id:)
Expand Down

0 comments on commit a6a3632

Please sign in to comment.