diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d86775..6c9db79 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,11 @@ - `Automations#get_subscriber_activity` takes `filter[:search]`, sent as `filter[search]`. The old `filter[:keyword]` is now sent as `filter[search]` too; the API rejected `filter[keyword]` with a 400 - `AutomationReports#step_subscribers` and `#trigger_subscribers` send an Array `filter[:id]` as one comma-separated value - `Automations#get_subscriber_activity` takes `with_subscribers: true` to include each run's subscriber. It sends `with_subscribers=1` only when true, because the API turns it on for any value +- Add the `Emails` class for the emails built with the simple editor: get an email, its HTML and its blocks, insert, update, delete, move and validate blocks, update and validate the design settings, save a template, and list, save and restore versions +- Add `BrandStyles#get` and `Files#list` +- Add `Campaigns::EDITOR_SIMPLE`, and document `editor` and `template_id` for the emails of `Campaigns#create` +- Add the optional `idempotency_key` argument to the email writes +- The new methods return an `HTTP::Response` with `api_error` (a `MailerLite::ApiError` with `status`, `code`, `etag`, `errors` and `api_message`) and `idempotent_replay?`. They do not raise for an API error ## [2.0.0] - 2024-12-11 - *BREAKING CHANGE* - Please check the README file, dotenv is now optional diff --git a/README.md b/README.md index d912e77..48a502a 100644 --- a/README.md +++ b/README.md @@ -55,11 +55,32 @@ For more information how to obtain an API key visit the [following link](https:/ - [List all campaigns](#list-all-campaigns) - [Get a campaign](#get-a-campaign) - [Create a campaign](#create-a-campaign) + - [Create a campaign with the simple editor](#create-a-campaign-with-the-simple-editor) - [Update a campaign](#update-a-campaign) - [Schedule a campaign](#schedule-a-campaign) - [Cancel a campaign](#cancel-a-campaign) - [Delete a campaign](#delete-a-campaign) - [Get subscribers activity for a campaign](#get-subscribers-activity-for-a-campaign) + - [Emails](#emails) + - [Get an email](#get-an-email) + - [Get the HTML of an email](#get-the-html-of-an-email) + - [Get a block](#get-a-block) + - [Insert a block](#insert-a-block) + - [Update a block](#update-a-block) + - [Delete a block](#delete-a-block) + - [Move a block](#move-a-block) + - [Validate a block](#validate-a-block) + - [Update the design settings](#update-the-design-settings) + - [Validate the design settings](#validate-the-design-settings) + - [Save an email as a template](#save-an-email-as-a-template) + - [List the versions of an email](#list-the-versions-of-an-email) + - [Save a version of an email](#save-a-version-of-an-email) + - [Restore a version of an email](#restore-a-version-of-an-email) + - [Retry a write with an idempotency key](#retry-a-write-with-an-idempotency-key) + - [Brand styles](#brand-styles) + - [Get the brand styles](#get-the-brand-styles) + - [Files](#files) + - [List all files](#list-all-files) - [Forms](#forms) - [List all forms](#list-all-forms) - [Get a form](#get-a-form) @@ -487,6 +508,36 @@ campaigns.create( ) ``` +### Create a campaign with the simple editor + + + +To build the email with the simple editor, set `editor` to `MailerLite::Campaigns::EDITOR_SIMPLE`, and do not send `content`. Then edit the email with [the email methods](#emails). + +- `template_id` is optional. It is a shared template of the simple editor that the email starts from. It needs `editor`. +- All emails of a campaign must have the same `editor` and `template_id`. +- Only `create` accepts `editor` and `template_id`. `update` does not. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +campaigns = MailerLite::Campaigns.new + +response = campaigns.create( + name: "Test Campaign", + type: "regular", + emails: [{ + subject: "This is a test campaign", + from_name: "Test Man", + from: "testuser@mailerlite.com", + editor: MailerLite::Campaigns::EDITOR_SIMPLE + }] +) + +email_id = JSON.parse(response.body)['data']['emails'][0]['id'] +``` + ### Update a campaign @@ -576,6 +627,399 @@ campaign_id = 123456 campaigns.activity(campaign_id) ``` +## Emails + + + +These methods edit emails built with the simple editor. To create such an email, [create a campaign with the simple editor](#create-a-campaign-with-the-simple-editor). The ID of the email is in `data.emails[0].id` of the response. + +- IDs are strings of digits. You can also give them as integers. An empty ID raises `MailerLite::EmptyIdError`, and an ID that does not contain only digits raises `MailerLite::InvalidIdError`. The SDK sends no request in these cases. +- The SDK checks only the IDs in the URL path, and the settings of `update_settings`: they must be a Hash without an `etag` key. The SDK sends all other values as you give them, and the API checks them. For a value that is not valid, the API returns `422` with the `errors` for each field. +- The methods return an `HTTP::Response`, like the other methods. Use `response.code` for the status code, `response.headers` for the headers and `JSON.parse(response.body)` for the body. +- The methods do not raise an error for a `4xx` or `5xx` status. `response.api_error` is `nil` for a `2xx` status. For other statuses, it is a `MailerLite::ApiError` with `status`, `code`, `etag`, `api_message` and `errors`. You can raise it. +- Each write needs the etag from the last response for the email, and returns a new etag. The etag covers the whole email, so send the writes to one email one after another. +- If the email changed after you read it, the write returns `409`, and `response.api_error.code` is `MailerLite::Emails::VERSION_CONFLICT`. Then `response.api_error.etag` is the current etag. Get the email again, and then send the write again with the current etag. +- The keys of `editor_content` are camelCase, for example `textAlign`. The SDK sends them as you give them. + +### Get an email + + + +Returns the email with its settings and blocks, and the etag of the email. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.get('123456') + +body = JSON.parse(response.body) +email = body['data'] +etag = body['etag'] +``` + +### Get the HTML of an email + + + +Returns the HTML that the email sends. The API can return a temporary `503` error. If it does, try again later. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.get_html('123456') + +html = JSON.parse(response.body)['data']['html'] if response.code == 200 +``` + +### Get a block + + + +Returns the block and its place in the email: `placement` has the IDs of the blocks `after` and `before` it, or `nil`. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.get_block(email_id: '123456', block_id: '57') + +block = JSON.parse(response.body)['data'] +``` + +### Insert a block + + + +Use the block types in `MailerLite::Emails::BlockType`. `editor_content` can be empty. Without `placement`, the API puts the block at the end of the email. The positions are in `MailerLite::Emails::BlockPosition`. The `BEFORE` and `AFTER` positions also need a `block_id`. The SDK sends `placement` as you give it. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +email_id = '123456' +etag = JSON.parse(emails.get(email_id).body)['etag'] + +response = emails.create_block( + email_id: email_id, + etag: etag, + type: MailerLite::Emails::BlockType::PARAGRAPH, + editor_content: { attrs: { textAlign: 'left' }, content: [{ type: 'text', text: 'Hello' }] }, + placement: { position: MailerLite::Emails::BlockPosition::AT_START } +) + +body = JSON.parse(response.body) +block_id = body['data']['id'] +etag = body['etag'] +``` + +### Update a block + + + +The new `editor_content` replaces the whole content of the block. The API removes the keys that you do not send. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.update_block( + email_id: '123456', + block_id: '57', + etag: 'etag-from-the-last-response', + editor_content: { attrs: { textAlign: 'center' }, content: [{ type: 'text', text: 'Hello again' }] } +) + +etag = JSON.parse(response.body)['etag'] +``` + +### Delete a block + + + +Also deletes the blocks in it. The response has only the new etag. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.delete_block(email_id: '123456', block_id: '57', etag: 'etag-from-the-last-response') + +etag = JSON.parse(response.body)['etag'] +``` + +### Move a block + + + +The `BEFORE` and `AFTER` positions also need a `block_id`. The SDK sends `placement` as you give it. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.move_block( + email_id: '123456', + block_id: '57', + etag: 'etag-from-the-last-response', + placement: { position: MailerLite::Emails::BlockPosition::AFTER, block_id: '12' } +) + +etag = JSON.parse(response.body)['etag'] +``` + +### Validate a block + + + +Checks a block before you insert it. It needs no email and no etag. An invalid block is not an error: the response has `valid` set to `false` and the `errors` for each field. + +The block in this example is not valid, because `sideways` is not a valid `textAlign`. The response has `valid: false` and `errors`. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.validate_block( + type: MailerLite::Emails::BlockType::PARAGRAPH, + editor_content: { attrs: { textAlign: 'sideways' } } +) + +body = JSON.parse(response.body) +puts body['errors'] unless body['valid'] +``` + +### Update the design settings + + + +Send only the keys to change, in the shape of `settings` in the email. The groups are `brand`, `layout`, `typography`, `button` and `footer`. + +- The SDK sends exactly the keys of the Hash. A key that is not in the Hash does not change. +- To unset a brand colour, send an empty string. The API stores the value empty, and the email then uses the account value. +- To unset a footer text, send an empty editor document: `{ editor_content: {} }` or `{ editor_content: { content: [] } }`. +- Other colours, sizes, `button.border_radius` and `brand.style` cannot be empty. An empty string gives a `422` error. +- Send all style values as strings, for example `'16'` and not `16`. +- The API stores each value that you send, also a value that the email inherits from your account. Then the email no longer follows your account for that value. +- `footer.social_links` replaces the whole list. Keep the `link_id` of each link to keep its click history. +- `brand.mode` is one of `MailerLite::Emails::BrandMode`. To apply a preset palette, send its `identifier` from the brand styles in `brand.style`. +- Do not put `etag` in the settings. Use the `etag` argument. +- If the API removed unsafe values, the response has `rejected` with the keys of these values. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.update_settings( + email_id: '123456', + etag: 'etag-from-the-last-response', + settings: { + brand: { mode: MailerLite::Emails::BrandMode::CUSTOM, background_color: '#f4f4f4' }, + typography: { paragraph: { p1: { size: '18' } } } + } +) + +body = JSON.parse(response.body) +etag = body['etag'] +puts body['rejected']['keys'] if body['rejected'] +``` + +### Validate the design settings + + + +Checks a change with the rules of the update, and saves nothing. It needs no etag. Invalid settings are not an error: the response has `valid` set to `false` and the `errors` for each field. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.validate_settings(email_id: '123456', settings: { button: { border_radius: '8' } }) + +body = JSON.parse(response.body) +puts body['errors'] unless body['valid'] +``` + +### Save an email as a template + + + +Copies the email to a new template. The API cannot delete templates. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.create_template(email_id: '123456', name: 'Monthly newsletter') + +template_id = JSON.parse(response.body)['data']['id'] +``` + +### List the versions of an email + + + +A version is a saved copy of the content and the settings of an email. The list starts with the newest version. `current` marks the version that the email has now. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.list_versions('123456', page: 1, limit: 10) + +versions = JSON.parse(response.body)['data'] +``` + +### Save a version of an email + + + +Writes through the API do not save versions. If nothing changed after the last version, the API saves no new version and returns the last version. `response.code` is `201` for a new version and `200` for the last version. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.create_version('123456') + +version_id = JSON.parse(response.body)['data']['id'] +is_new = response.code == 201 +``` + +### Restore a version of an email + + + +Puts the email back to the version, and returns the full email with the new etag. Before the restore, the API saves the current state as a version, so you can undo the restore. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +emails = MailerLite::Emails.new + +response = emails.restore_version(email_id: '123456', version_id: '901', etag: 'etag-from-the-last-response') + +etag = JSON.parse(response.body)['etag'] +``` + +### Retry a write with an idempotency key + + + +If a write fails with a network error, you do not know if the API did the write. Give the write an `idempotency_key`, and send it again with the same key and the same arguments. If the first request was a success, the API returns the stored response and does not do the write two times. Then `response.idempotent_replay?` is `true`. + +- Use a new key for each write. The API keeps a key for 24 hours. +- The key must be 1 to 255 printable ASCII characters. The SDK sends the key as you give it. For a key that is not valid, the API returns `400`. +- The same key with different arguments returns `422`. If the first request is still running, the API returns `409` without a `code`. +- These methods accept a key: `create_block`, `update_block`, `delete_block`, `move_block`, `update_settings`, `create_template`, `create_version` and `restore_version`. + +```ruby +require "mailerlite-ruby" +require "securerandom" + +# Initialize the class +emails = MailerLite::Emails.new + +args = { + email_id: '123456', + etag: 'etag-from-the-last-response', + type: MailerLite::Emails::BlockType::DIVIDER, + editor_content: {}, + idempotency_key: SecureRandom.uuid +} + +begin + response = emails.create_block(**args) +rescue HTTP::ConnectionError, HTTP::TimeoutError + # Network error: send the write again with the same key and the same arguments. + response = emails.create_block(**args) +end + +error = response.api_error +raise error if error + +puts JSON.parse(response.body)['data']['id'], response.idempotent_replay? +``` + +## Brand styles + + + +### Get the brand styles + + + +Returns the palettes of your account: `brand` (your brand styles, or `nil` if your account has none), `default` and the `presets`. Match a palette on its `identifier`, not on its `name`. To apply a preset to an email, [update the design settings](#update-the-design-settings) with `{ brand: { style: identifier } }`. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +brand_styles = MailerLite::BrandStyles.new + +response = brand_styles.get + +identifiers = JSON.parse(response.body)['data']['presets'].map { |preset| preset['identifier'] } +``` + +## Files + + + +### List all files + + + +Returns the files of your media library. Use their `url` in image blocks. `width` and `height` are `nil` for files that are not images. + +- `filter`: `name` (a part of the file name) and `type` (one of `MailerLite::Files::FileType`). +- `sort`: one of `MailerLite::Files::FileSort`. The default is newest first. +- The SDK does not send `nil` values. + +```ruby +require "mailerlite-ruby" + +# Initialize the class +files = MailerLite::Files.new + +response = files.list( + filter: { name: 'summer sale', type: MailerLite::Files::FileType::IMAGE }, + sort: MailerLite::Files::FileSort::SIZE_DESC, + page: 1, + limit: 25 +) + +urls = JSON.parse(response.body)['data'].map { |file| file['url'] } +``` + ## Forms diff --git a/lib/mailerlite.rb b/lib/mailerlite.rb index 634a075..0fce1f4 100644 --- a/lib/mailerlite.rb +++ b/lib/mailerlite.rb @@ -3,6 +3,10 @@ require_relative 'mailerlite/client' require_relative 'mailerlite/version' require_relative 'mailerlite/query_params' +require_relative 'mailerlite/errors' +require_relative 'mailerlite/params' +require_relative 'mailerlite/api_response' +require_relative 'mailerlite/request' require_relative 'mailerlite/subscribers/subscribers' require_relative 'mailerlite/campaigns/campaigns' require_relative 'mailerlite/forms/forms' @@ -19,3 +23,6 @@ require_relative 'mailerlite/batch/batch' require_relative 'mailerlite/timezones/timezones' require_relative 'mailerlite/ecommerce/ecommerce' +require_relative 'mailerlite/emails/emails' +require_relative 'mailerlite/brand_styles/brand_styles' +require_relative 'mailerlite/files/files' diff --git a/lib/mailerlite/api_response.rb b/lib/mailerlite/api_response.rb new file mode 100644 index 0000000..8e22c21 --- /dev/null +++ b/lib/mailerlite/api_response.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +module MailerLite + # Helpers that `Emails`, `BrandStyles` and `Files` add to each `HTTP::Response` that they return. + # + # The response is still an `HTTP::Response`. Use `response.code` for the status code, + # `response.headers` for the headers and `response.parse` for the decoded body. + module ApiResponse + # Returns true if the API returned the stored response of an earlier request with the same idempotency key. + # + # @return [Boolean] true if the `Idempotent-Replayed` header is "true" + def idempotent_replay? + # A proxy can change the case of the value, or send the header two times. + headers.get('Idempotent-Replayed').any? { |value| value.strip.casecmp?('true') } + end + + # Returns the error of the response. + # + # @return [MailerLite::ApiError, nil] nil for a 2xx status, otherwise an error that you can raise + def api_error + status.success? ? nil : ApiError.from_response(self) + end + end +end diff --git a/lib/mailerlite/brand_styles/brand_styles.rb b/lib/mailerlite/brand_styles/brand_styles.rb new file mode 100644 index 0000000..a69d961 --- /dev/null +++ b/lib/mailerlite/brand_styles/brand_styles.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +module MailerLite + # This is a class for the brand styles from MailerLite API. + class BrandStyles + attr_reader :client + + # Inits the `BrandStyles` class with the specified `client`. + # + # @param client [MailerLite::Client] the `Client` instance to use + def initialize(client: MailerLite::Client.new) + @client = client + end + + # Returns the palettes of the account: `brand` (the brand styles of the account, or nil if it has none), + # `default` and the `presets`. Match a palette on its `identifier`, not on its `name`. + # To apply a preset to an email, send its `identifier` in `brand.style` with `Emails#update_settings`. + # + # @return [HTTP::Response] the response from the API, with the `MailerLite::ApiResponse` methods + def get + Request.call(client, :get, '/brand-styles') + end + end +end diff --git a/lib/mailerlite/campaigns/campaigns.rb b/lib/mailerlite/campaigns/campaigns.rb index dfe2e70..a4d5242 100644 --- a/lib/mailerlite/campaigns/campaigns.rb +++ b/lib/mailerlite/campaigns/campaigns.rb @@ -3,6 +3,9 @@ module MailerLite # This is a class for manipulating the Campaigns from MailerLite API. class Campaigns + # The value of `editor` in the emails of `create` for the simple editor. + EDITOR_SIMPLE = 'simple' + attr_reader :client # Inits the `Campaigns` class with the specified `client`. @@ -34,7 +37,10 @@ def get(filter:, limit: nil, page: nil) # @param name [String] Maximum string length of 255 characters # @param language_id [integer] Used to define the language in the unsubscribe template. Must be a valid language id. Defaults to english # @param type [String] Must be one of the following: regular, ab, resend. Type resend is only available for accounts on growing or advanced plans - # @param emails [Array] Must contain 1 email object item + # @param emails [Array] Must contain 1 email object item. The SDK sends each email as it is. An email can also have these keys: + # - `editor`: the only accepted value is `simple`, which selects the simple editor instead of the drag-and-drop builder. It has to be the same across every email in the payload; a mixed array is rejected. Setting it prohibits `emails.*.content`. Use `EDITOR_SIMPLE`. + # - `template_id`: the template the new email starts from. Allowed only when `editor` is `simple`, accepts only a template from the shared gallery, and also has to be the same across every email. + # Then edit the email with `MailerLite::Emails`. Its ID is in `data.emails[0].id` of the response. # @param groups [Array] Must contain valid group ids belonging to the account # @param segments [Array] Must contain valid segment ids belonging to the account. If both groups and segments are provided, only segments are used # @param ab_settings [Array] only if type is ab - All items of the array are required @@ -82,6 +88,7 @@ def create(name:, type:, emails:, language_id: nil, groups: nil, segments: nil, end # Update a new campaign with the specified details. + # Only `create` accepts `editor` and `template_id`. # # @param campaign_id [Integer] the ID of the campaign to update # @param name [String] Maximum string length of 255 characters diff --git a/lib/mailerlite/emails/emails.rb b/lib/mailerlite/emails/emails.rb new file mode 100644 index 0000000..483ef2c --- /dev/null +++ b/lib/mailerlite/emails/emails.rb @@ -0,0 +1,294 @@ +# frozen_string_literal: true + +module MailerLite + # This is a class for the emails built with the simple editor. + # + # To create such an email, create a campaign with `editor: MailerLite::Campaigns::EDITOR_SIMPLE` in the email. + # The ID of the email is in `data.emails[0].id` of the response. + # + # IDs are Strings of the digits 0-9. You can also give them as Integers. An empty ID raises + # `MailerLite::EmptyIdError`, and an ID with other characters raises `MailerLite::InvalidIdError`. + # + # Each method returns the `HTTP::Response` with the `MailerLite::ApiResponse` methods. The methods do not raise + # for a 4xx or 5xx status: use `response.api_error`. The SDK checks only the IDs in the URL path, and the settings + # Hash of `update_settings`. It sends all other values as you give them, and the API checks them. + # + # Each write needs the etag from the last response for the email, and returns a new etag. The etag covers the + # whole email, so send the writes to one email one after another. If the email changed after you read it, the + # API returns 409 and `response.api_error.code` is `VERSION_CONFLICT`. Then `response.api_error.etag` is the + # current etag. + # + # Idempotency keys: if a write fails with a network error, you do not know if the API did the write. Give an + # `idempotency_key` to the write, and send it again with the same key and the same arguments. If the first request + # was a success, the API returns the stored response and does not do the write two times. Then + # `response.idempotent_replay?` is true. Use a new key for each write. The API keeps a key for 24 hours. + # The key must be 1 to 255 printable ASCII characters. For a key that is not valid, the API returns 400. + class Emails + # The error code of a write with an etag that is not the current etag of the email. + VERSION_CONFLICT = 'version_conflict' + + # Block types. The API can also return types that are not in this list. + module BlockType + BLOCKQUOTE = 'blockquote' + BULLETED_LIST = 'bulleted_list' + BUTTON = 'button' + CODE = 'code' + DIVIDER = 'divider' + HEADING = 'heading' + IMAGE = 'image' + NUMBERED_LIST = 'numbered_list' + PARAGRAPH = 'paragraph' + SOCIAL_ICON = 'social_icon' + # Only reads return this type. You cannot insert a block of this type. + TITLE = 'title' + VIDEO = 'video' + end + + # Positions of a block, for `placement`. `BEFORE` and `AFTER` also need a `block_id`. + module BlockPosition + AT_START = 'start' + AT_END = 'end' + BEFORE = 'before' + AFTER = 'after' + end + + # Where the palette of an email comes from, in `settings[:brand][:mode]`. + module BrandMode + ACCOUNT = 'account' + TEMPLATE = 'template' + CUSTOM = 'custom' + end + + attr_reader :client + + # Inits the `Emails` class with the specified `client`. + # + # @param client [MailerLite::Client] the `Client` instance to use + def initialize(client: MailerLite::Client.new) + @client = client + end + + # Returns the email with its settings and blocks, and the etag of the email. + # + # @param email_id [String, Integer] the ID of the email + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def get(email_id) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :get, "/emails/#{email_id}") + end + + # Returns the HTML that the email sends, and the etag of the email. + # The API can return a temporary 503 error. Then try again later. + # + # @param email_id [String, Integer] the ID of the email + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def get_html(email_id) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :get, "/emails/#{email_id}/html") + end + + # Returns the block and its place in the email, and the etag of the email. + # `placement` has the IDs of the blocks `after` and `before` it, or nil. + # + # @param email_id [String, Integer] the ID of the email + # @param block_id [String, Integer] the ID of the block + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid + def get_block(email_id:, block_id:) + email_id = Params.path_id(email_id, 'email_id') + block_id = Params.path_id(block_id, 'block_id') + Request.call(client, :get, "/emails/#{email_id}/blocks/#{block_id}") + end + + # Inserts a block in the email. Returns the new block and the new etag of the email. + # + # @param email_id [String, Integer] the ID of the email + # @param etag [String] the etag from the last response for the email + # @param type [String] the block type, see `BlockType`. You cannot insert `title`. + # @param editor_content [Hash] the content of the block. It can be empty. Its keys are camelCase, for example `textAlign`. + # @param placement [Hash, nil] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id`. + # Without it, the API puts the block at the end of the email. + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid + def create_block(email_id:, etag:, type:, editor_content:, placement: nil, idempotency_key: nil) + email_id = Params.path_id(email_id, 'email_id') + body = block_body(type, editor_content, placement).merge('etag' => etag) + Request.call(client, :post, "/emails/#{email_id}/blocks", json: body, idempotency_key: idempotency_key) + end + + # Updates a block of the email. The new content replaces the whole content of the block: the API removes the + # keys that you do not send. Returns the block and the new etag of the email. + # + # @param email_id [String, Integer] the ID of the email + # @param block_id [String, Integer] the ID of the block + # @param etag [String] the etag from the last response for the email + # @param editor_content [Hash] the new content of the block. Its keys are camelCase, for example `textAlign`. + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid + def update_block(email_id:, block_id:, etag:, editor_content:, idempotency_key: nil) + email_id = Params.path_id(email_id, 'email_id') + block_id = Params.path_id(block_id, 'block_id') + body = { 'editor_content' => editor_content, 'etag' => etag } + Request.call(client, :patch, "/emails/#{email_id}/blocks/#{block_id}", json: body, idempotency_key: idempotency_key) + end + + # Deletes a block of the email, and the blocks in it. The response has only the new etag of the email, + # so the method returns the response and not true. + # + # @param email_id [String, Integer] the ID of the email + # @param block_id [String, Integer] the ID of the block + # @param etag [String] the etag from the last response for the email + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid + def delete_block(email_id:, block_id:, etag:, idempotency_key: nil) + email_id = Params.path_id(email_id, 'email_id') + block_id = Params.path_id(block_id, 'block_id') + Request.call(client, :delete, "/emails/#{email_id}/blocks/#{block_id}", json: { 'etag' => etag }, idempotency_key: idempotency_key) + end + + # Moves a block of the email. Returns the block, its new place in the email, and the new etag of the email. + # + # @param email_id [String, Integer] the ID of the email + # @param block_id [String, Integer] the ID of the block to move + # @param etag [String] the etag from the last response for the email + # @param placement [Hash] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id` + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid + def move_block(email_id:, block_id:, etag:, placement:, idempotency_key: nil) + email_id = Params.path_id(email_id, 'email_id') + block_id = Params.path_id(block_id, 'block_id') + body = { 'placement' => placement, 'etag' => etag } + Request.call(client, :post, "/emails/#{email_id}/blocks/#{block_id}/move", json: body, idempotency_key: idempotency_key) + end + + # Validates a block before you insert it. It needs no email and no etag. An invalid block is not an error: + # the response has `valid` set to false and the `errors` for each field. + # + # @param type [String] the block type, see `BlockType` + # @param editor_content [Hash] the content of the block. Its keys are camelCase, for example `textAlign`. + # @param placement [Hash, nil] `position` (see `BlockPosition`) and, for `before` and `after`, `block_id` + # @return [HTTP::Response] the response from the API, with `valid`, `errors` and `schema` + def validate_block(type:, editor_content:, placement: nil) + Request.call(client, :post, '/emails/blocks/validate', json: block_body(type, editor_content, placement)) + end + + # Updates the design settings of the email. Returns the settings and the new etag of the email. + # + # Send only the keys to change, in the shape of `settings` in the response of `get`. The groups are `brand`, + # `layout`, `typography`, `button` and `footer`. The SDK sends exactly the keys of the Hash: + # - a key that is not in the Hash does not change; + # - an empty String unsets a brand colour, and the email then uses the account value; + # - an empty editor document, `{ editor_content: {} }` or `{ editor_content: { content: [] } }`, unsets a footer text; + # - other colours, sizes, `button.border_radius` and `brand.style` cannot be empty: an empty String gives a `422` error; + # - any other value is the new value. Send style values as Strings, for example '16'. + # + # The API stores each value that you send, also a value that the email inherits from the account. + # `footer.social_links` replaces the whole list: keep the `link_id` of each link to keep its click history. + # To apply a preset palette, send its `identifier` from `BrandStyles#get` in `brand.style`. + # The response can have `rejected` when the API removed unsafe values. + # + # @param email_id [String, Integer] the ID of the email + # @param etag [String] the etag from the last response for the email + # @param settings [Hash] the settings to change, without `etag` + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + # @raise [ArgumentError] if the settings contain an `etag` key + # @raise [TypeError] if the settings are not a Hash + def update_settings(email_id:, etag:, settings:, idempotency_key: nil) + email_id = Params.path_id(email_id, 'email_id') + body = Params.settings(settings).merge('etag' => etag) + Request.call(client, :patch, "/emails/#{email_id}/settings", json: body, idempotency_key: idempotency_key) + end + + # Validates a change to the design settings of the email with the rules of `update_settings`, and saves nothing. + # It needs no etag. Invalid settings are not an error: the response has `valid` set to false and the `errors` + # for each field. The response can also have `rejected`. + # + # @param email_id [String, Integer] the ID of the email + # @param settings [Hash] the settings that you want to send to `update_settings`, without `etag` + # @return [HTTP::Response] the response from the API, with `valid`, `errors` and `schema` + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def validate_settings(email_id:, settings:) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :post, "/emails/#{email_id}/settings/validate", json: settings) + end + + # Saves the email as a new template with the name. The API cannot delete templates. + # + # @param email_id [String, Integer] the ID of the email + # @param name [String] the name of the template + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def create_template(email_id:, name:, idempotency_key: nil) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :post, "/emails/#{email_id}/templates", json: { 'name' => name }, idempotency_key: idempotency_key) + end + + # Returns the saved versions of the email, newest first. `current` marks the version that the email has now. + # + # @param email_id [String, Integer] the ID of the email + # @param page [Integer] the page number of the results to return + # @param limit [Integer] the maximum number of versions to return, from 1 to 100 + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def list_versions(email_id, page: nil, limit: nil) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :get, "/emails/#{email_id}/versions", query: Params.query(page: page, limit: limit)) + end + + # Saves the content and the settings of the email as a new version. If nothing changed after the last version, + # the API saves no new version and returns the last version. The status code (`response.code`) is 201 for a new + # version and 200 for the last version. Both are a success. + # + # @param email_id [String, Integer] the ID of the email + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if the ID is not valid + def create_version(email_id, idempotency_key: nil) + email_id = Params.path_id(email_id, 'email_id') + Request.call(client, :post, "/emails/#{email_id}/versions", idempotency_key: idempotency_key) + end + + # Restores the email to a version. Returns the email in the shape of `get`, with the new etag. Before the + # restore, the API saves the current state as a version, so you can undo the restore. + # + # @param email_id [String, Integer] the ID of the email + # @param version_id [String, Integer] the ID of the version + # @param etag [String] the etag from the last response for the email + # @param idempotency_key [String, nil] a key to send the write again safely, see "Idempotency keys" in the class + # documentation + # @return [HTTP::Response] the response from the API + # @raise [MailerLite::EmptyIdError, MailerLite::InvalidIdError, TypeError] if an ID is not valid + def restore_version(email_id:, version_id:, etag:, idempotency_key: nil) + email_id = Params.path_id(email_id, 'email_id') + version_id = Params.path_id(version_id, 'version_id') + Request.call(client, :post, "/emails/#{email_id}/versions/#{version_id}/restore", json: { 'etag' => etag }, idempotency_key: idempotency_key) + end + + private + + def block_body(type, editor_content, placement) + body = { + 'type' => type, + 'editor_content' => editor_content + } + body['placement'] = placement unless placement.nil? + body + end + end +end diff --git a/lib/mailerlite/errors.rb b/lib/mailerlite/errors.rb new file mode 100644 index 0000000..9ea949a --- /dev/null +++ b/lib/mailerlite/errors.rb @@ -0,0 +1,88 @@ +# frozen_string_literal: true + +require 'json' + +module MailerLite + # The base class of the errors of the SDK. + class Error < StandardError; end + + # An error response (4xx or 5xx) from the API. + # + # The SDK does not raise it. Get it with `response.api_error` and raise it if you want to. + # It is not an `HTTP::Error`, so code that retries on network errors does not also retry an API error. + # It keeps only plain values, so `Marshal.dump` works. + # + # Note: `HTTP::Response#code` is the numeric status. `ApiError#code` is the String code of the API, + # for example `"version_conflict"`. The numeric status is in `ApiError#status`. + class ApiError < Error + # @return [Integer] the HTTP status code, for example 409 + attr_reader :status + # @return [String, nil] the error code of the API, for example "version_conflict" + attr_reader :code + # @return [String, nil] the current etag of the email, for a 409 version conflict + attr_reader :etag + # @return [Hash, nil] the error messages for each field, for some 422 responses + attr_reader :errors + # @return [String, nil] the message of the API + attr_reader :api_message + # @return [String] the response body as it is + attr_reader :body + # @return [Hash] the response headers + attr_reader :headers + + # Makes an error from a response. It works for the responses of all methods of the SDK. + # A body that is not a JSON object gives nil fields. + # + # @param response [HTTP::Response] the response + # @return [MailerLite::ApiError] the error + def self.from_response(response) + body = response.body.to_s + data = parse(body) + new(status: response.code, reason: response.reason, body: body, headers: response.headers.to_h, + code: data['code'], etag: data['etag'], errors: data['errors'], api_message: data['message']) + end + + def self.parse(body) + data = JSON.parse(body) + data.is_a?(Hash) ? data : {} + rescue JSON::ParserError, EncodingError + {} + end + private_class_method :parse + + # @param status [Integer] the HTTP status code + # @param reason [String, nil] the reason phrase of the status + # @param code [String, nil] the error code of the API + # @param etag [String, nil] the current etag of the email + # @param errors [Hash, nil] the error messages for each field + # @param api_message [String, nil] the message of the API + # @param body [String] the response body + # @param headers [Hash] the response headers + def initialize(status:, reason: nil, code: nil, etag: nil, errors: nil, api_message: nil, body: '', headers: {}) + @status = status + @code = code + @etag = etag + @errors = errors + @api_message = api_message + @body = body + @headers = headers + super(build_message(reason)) + end + + private + + # For example "409 Conflict (version_conflict): The email was changed." + def build_message(reason) + text = [status, reason].compact.join(' ') + text += " (#{code})" if code + text += ": #{api_message}" if api_message + text + end + end + + # An ID for the URL path is empty. The SDK sends no request. + class EmptyIdError < ArgumentError; end + + # An ID for the URL path does not contain only the digits 0-9. The SDK sends no request. + class InvalidIdError < ArgumentError; end +end diff --git a/lib/mailerlite/files/files.rb b/lib/mailerlite/files/files.rb new file mode 100644 index 0000000..9965682 --- /dev/null +++ b/lib/mailerlite/files/files.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +module MailerLite + # This is a class for the files of the media library from MailerLite API. + class Files + # File types for `filter: { type: ... }`. The API can also return types that are not in this list. + module FileType + IMAGE = 'image' + PDF = 'pdf' + EPUB = 'epub' + end + + # Sort values. The values that start with `-` sort in descending order. + module FileSort + CREATED_AT = 'created_at' + CREATED_AT_DESC = '-created_at' + NAME = 'name' + NAME_DESC = '-name' + SIZE = 'size' + SIZE_DESC = '-size' + end + + attr_reader :client + + # Inits the `Files` class with the specified `client`. + # + # @param client [MailerLite::Client] the `Client` instance to use + def initialize(client: MailerLite::Client.new) + @client = client + end + + # Returns the files of the media library. Use their `url` in image blocks. + # `width` and `height` are nil for files that are not images. The SDK does not send nil values. + # + # @param filter [Hash, nil] `name` (a part of the file name) and `type` (see `FileType`) + # @param sort [String, nil] see `FileSort`. The default is `-created_at`. + # @param page [Integer, nil] the page number of the results to return + # @param limit [Integer, nil] the maximum number of files to return, from 1 to 100 + # @return [HTTP::Response] the response from the API, with the `MailerLite::ApiResponse` methods + # @raise [TypeError] if the filter is not a Hash + def list(filter: nil, sort: nil, page: nil, limit: nil) + Request.call(client, :get, '/files', query: Params.query(filter: filter, sort: sort, page: page, limit: limit)) + end + end +end diff --git a/lib/mailerlite/params.rb b/lib/mailerlite/params.rb new file mode 100644 index 0000000..538f1a7 --- /dev/null +++ b/lib/mailerlite/params.rb @@ -0,0 +1,58 @@ +# frozen_string_literal: true + +module MailerLite + # Checks and helpers for the request parameters of the resources. + # The SDK checks only the IDs in the URL path and the values that its code reads. The API checks all other values. + # Each check raises before the request, so the SDK sends no request when a value is not valid. + module Params + module_function + + # Use \A and \z: `$` and \Z also match before a final new line. + # Use [0-9]: [[:digit:]] also matches digits that are not ASCII. + ID_PATTERN = /\A[0-9]+\z/ + + def path_id(value, name) + raise EmptyIdError, "`#{name}` must not be empty." if value.nil? || value == '' + + raise TypeError, "`#{name}` type is not valid. Expected String or Integer, got #{value.class}." unless value.is_a?(String) || value.is_a?(Integer) + + id = value.to_s + # match? raises for a String with invalid bytes, so check the encoding first. + raise InvalidIdError, "`#{name}` must contain only the digits 0-9, got #{id.inspect}." unless id.valid_encoding? && id.ascii_only? && id.match?(ID_PATTERN) + + id + end + + def require_hash(value, name) + raise TypeError, "`#{name}` type is not valid. Expected Hash, got #{value.class}." unless value.is_a?(Hash) + + value + end + + def settings(settings) + require_hash(settings, 'settings') + # The body has the settings and the etag at the same level. An etag key in the settings can hide the etag argument. + raise ArgumentError, '`settings` must not contain `etag`. Use the `etag` argument.' if settings.key?(:etag) || settings.key?('etag') + + settings + end + + # It drops nil values and keeps empty Strings. + def query(filter: nil, **params) + query = {} + unless filter.nil? + require_hash(filter, 'filter').each do |key, value| + query["filter[#{key}]"] = value unless value.nil? + end + end + params.each { |key, value| query[key.to_s] = value unless value.nil? } + query + end + + def idempotency_headers(key) + return {} if key.nil? + + { 'Idempotency-Key' => key } + end + end +end diff --git a/lib/mailerlite/request.rb b/lib/mailerlite/request.rb new file mode 100644 index 0000000..3745410 --- /dev/null +++ b/lib/mailerlite/request.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +require 'uri' + +module MailerLite + # Sends the requests of `Emails`, `BrandStyles` and `Files`. + module Request + module_function + + # It does not raise for a 4xx or 5xx status. + def call(client, method, path, json: nil, query: nil, idempotency_key: nil) + headers = Params.idempotency_headers(idempotency_key) + # Read the constant here, not when the file loads. + uri = URI("#{MAILERLITE_API_URL}#{path}") + uri.query = URI.encode_www_form(query) if query && !query.empty? + options = {} + # `body: nil.to_json` sends "null", so add `json:` only when there is a body. + options[:json] = json unless json.nil? + http = client.http + http = http.headers(headers) unless headers.empty? + http.request(method, uri, options).extend(ApiResponse) + end + end +end diff --git a/lib/mailerlite/version.rb b/lib/mailerlite/version.rb index 52dda1e..26a17ce 100644 --- a/lib/mailerlite/version.rb +++ b/lib/mailerlite/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module MailerLite - VERSION = '2.0.0' + VERSION = '2.1.0' end diff --git a/spec/api_response_rspec.rb b/spec/api_response_rspec.rb new file mode 100644 index 0000000..407cb8f --- /dev/null +++ b/spec/api_response_rspec.rb @@ -0,0 +1,140 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::ApiResponse do + include_context 'with the dummy API token' + + let(:url) { "#{MAILERLITE_API_URL}/emails/123" } + + def response_for(status:, body: '', headers: {}) + stub_request(:get, url).to_return(status: status, body: body, headers: headers) + MailerLite::Client.new.http.get(url).extend(described_class) + end + + describe '#idempotent_replay?' do + it 'is true for the value true' do + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => 'true' }).idempotent_replay?).to be(true) + end + + it 'reads the value without case and without spaces' do + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => 'True' }).idempotent_replay?).to be(true) + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => ' TRUE ' }).idempotent_replay?).to be(true) + end + + it 'is false when the header is not there' do + expect(response_for(status: 201).idempotent_replay?).to be(false) + end + + it 'is false for other values' do + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => 'false' }).idempotent_replay?).to be(false) + end + + it 'reads a header that comes two times' do + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => %w[true true] }).idempotent_replay?).to be(true) + expect(response_for(status: 201, headers: { 'Idempotent-Replayed' => %w[false false] }).idempotent_replay?).to be(false) + end + end + + describe '#api_error' do + it 'is nil for a 2xx status' do + response = response_for(status: 200, body: load_fixture('email').to_json) + expect(response.api_error).to be_nil + expect(response).to be_a(HTTP::Response) + end + + it 'has the code and the etag of a 409 version conflict' do + body = { message: 'The email was changed.', code: 'version_conflict', etag: '45' }.to_json + error = response_for(status: 409, body: body).api_error + + expect(error).to be_a(MailerLite::ApiError) + expect(error.status).to eq 409 + expect(error.code).to eq 'version_conflict' + expect(error.etag).to eq '45' + expect(error.api_message).to eq 'The email was changed.' + expect(error.errors).to be_nil + expect(error.message).to start_with('409') + expect(error.message).to include('(version_conflict): The email was changed.') + end + + it 'has no code for a 409 without a code' do + error = response_for(status: 409, body: { message: 'The campaign is not a draft.' }.to_json).api_error + + expect(error.status).to eq 409 + expect(error.code).to be_nil + expect(error.etag).to be_nil + expect(error.message).to include(': The campaign is not a draft.') + end + + it 'has the errors of a 422' do + body = { message: 'The etag field is required.', errors: { etag: ['The etag field is required.'] } }.to_json + error = response_for(status: 422, body: body).api_error + + expect(error.status).to eq 422 + expect(error.errors).to eq('etag' => ['The etag field is required.']) + expect(error.api_message).to eq 'The etag field is required.' + end + + it 'has no errors for a 422 with only a message' do + error = response_for(status: 422, body: { message: 'This email was not built with the simple editor.' }.to_json).api_error + + expect(error.errors).to be_nil + expect(error.api_message).to eq 'This email was not built with the simple editor.' + end + + it 'does not raise for a 503 with an HTML body' do + html = 'Service Unavailable' + error = response_for(status: 503, body: html, headers: { 'Content-Type' => 'text/html' }).api_error + + expect(error.status).to eq 503 + expect(error.api_message).to be_nil + expect(error.code).to be_nil + expect(error.body).to eq html + expect(error.headers['Content-Type']).to eq 'text/html' + expect(error.message).to start_with('503') + end + + it 'accepts a JSON body that is not an object' do + error = response_for(status: 500, body: '[1, 2]').api_error + + expect(error.status).to eq 500 + expect(error.api_message).to be_nil + expect(error.body).to eq '[1, 2]' + end + + it 'survives a Marshal round trip' do + body = { message: 'The email was changed.', code: 'version_conflict', etag: '45' }.to_json + error = response_for(status: 409, body: body).api_error + copy = Marshal.load(Marshal.dump(error)) + + expect(copy).to be_a(MailerLite::ApiError) + expect(copy.message).to eq error.message + expect([copy.status, copy.code, copy.etag, copy.api_message, copy.body]).to eq [409, 'version_conflict', '45', 'The email was changed.', body] + end + end + + describe MailerLite::ApiError do + it 'is a MailerLite::Error and not an HTTP::Error' do + expect(described_class.ancestors).to include(MailerLite::Error) + expect(described_class.ancestors).not_to include(HTTP::Error) + end + + it 'builds an error from any HTTP::Response' do + stub_request(:get, url).to_return(status: 404, body: { message: 'Not found.' }.to_json) + error = described_class.from_response(MailerLite::Client.new.http.get(url)) + + expect(error.status).to eq 404 + expect(error.api_message).to eq 'Not found.' + end + + it 'can be raised' do + stub_request(:get, url).to_return(status: 404, body: { message: 'Not found.' }.to_json) + error = described_class.from_response(MailerLite::Client.new.http.get(url)) + + expect { raise error }.to raise_error(described_class, /Not found\./) + end + end +end diff --git a/spec/brand_styles_rspec.rb b/spec/brand_styles_rspec.rb new file mode 100644 index 0000000..d66b58b --- /dev/null +++ b/spec/brand_styles_rspec.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::BrandStyles do + include_context 'with the dummy API token' + + let(:brand_styles) { described_class.new(client: MailerLite::Client.new) } + let(:url) { "#{MAILERLITE_API_URL}/brand-styles" } + + def stub_brand_styles(response) + stub_request(:get, url) + .with(headers: { 'Authorization' => 'Bearer dummy_token' }) { |req| req.body == '' && !req.headers.key?('Idempotency-Key') } + .to_return(status: 200, body: response.to_json, headers: { 'Content-Type' => 'application/json' }) + end + + describe '#get' do + it 'gets the palettes' do + stub = stub_brand_styles(load_fixture('brand_styles')) + + response = brand_styles.get + + expect(stub).to have_been_requested + expect(response).to be_a(HTTP::Response) + expect(response.api_error).to be_nil + data = JSON.parse(response.body.to_s)['data'] + expect(data['brand']['identifier']).to eq 'account' + expect(data['brand']['primary_color']).to eq '#2cb191' + expect(data['default']['identifier']).to eq 'default-brand' + expect(data['presets'].map { |preset| preset['identifier'] }).to eq %w[preset-business-casual preset-retro] + expect(data['presets'][1]['font_family']).to eq 'Courier New, monospace' + end + + it 'returns a null brand when the account has none' do + body = load_fixture('brand_styles') + body['data']['brand'] = nil + stub_brand_styles(body) + + data = JSON.parse(brand_styles.get.body.to_s)['data'] + + expect(data).to have_key('brand') + expect(data['brand']).to be_nil + expect(data['default']['identifier']).to eq 'default-brand' + end + end +end diff --git a/spec/campaigns_rspec.rb b/spec/campaigns_rspec.rb index b66d86e..ffba47b 100644 --- a/spec/campaigns_rspec.rb +++ b/spec/campaigns_rspec.rb @@ -4,6 +4,8 @@ require 'spec_helper' require 'vcr' require 'json' +require 'webmock/rspec' +require_relative 'support/json_fixture' # require "webmock/rspec" # Import the `Campaigns` class @@ -152,4 +154,44 @@ end end end + + describe '#create with the simple editor' do + include_context 'with the dummy API token' + + let(:url) { "#{MAILERLITE_API_URL}/campaigns" } + + def stub_create(body) + stub_request(:post, url) + .with(headers: { 'Authorization' => 'Bearer dummy_token' }) { |req| req.body == body } + .to_return(status: 201, body: load_fixture('campaign_simple_editor').to_json, headers: { 'Content-Type' => 'application/json' }) + end + + it 'has the value of the simple editor' do + expect(MailerLite::Campaigns::EDITOR_SIMPLE).to eq 'simple' + end + + it 'sends editor, template_id and reply_to, and no content' do + stub = stub_create('{"name":"Simple editor campaign","type":"regular","emails":[{"subject":"Hello","from_name":"Sender",' \ + '"from":"sender@example.com","reply_to":"reply@example.com","editor":"simple","template_id":789}]}') + + response = campaigns.create(name: 'Simple editor campaign', type: 'regular', + emails: [{ subject: 'Hello', from_name: 'Sender', from: 'sender@example.com', + reply_to: 'reply@example.com', editor: MailerLite::Campaigns::EDITOR_SIMPLE, template_id: 789 }]) + + expect(stub).to have_been_requested + email = JSON.parse(response.body.to_s)['data']['emails'][0] + expect(email['id']).to eq '123' + expect(email['type']).to eq 'builder_inline_email' + end + + it 'sends the same body as before without editor' do + stub = stub_create('{"name":"HTML campaign","type":"regular","emails":[{"subject":"Hello","from_name":"Sender",' \ + '"from":"sender@example.com","content":"

Hi

"}]}') + + campaigns.create(name: 'HTML campaign', type: 'regular', + emails: [{ subject: 'Hello', from_name: 'Sender', from: 'sender@example.com', content: '

Hi

' }]) + + expect(stub).to have_been_requested + end + end end diff --git a/spec/emails_rspec.rb b/spec/emails_rspec.rb new file mode 100644 index 0000000..3a08f0d --- /dev/null +++ b/spec/emails_rspec.rb @@ -0,0 +1,663 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::Emails do + include_context 'with the dummy API token' + + let(:client) { MailerLite::Client.new } + let(:emails) { described_class.new(client: client) } + + # A nil `key` matches only a request without the Idempotency-Key header. + def stub_api(method, path, body: '', response: {}, status: 200, query: nil, key: nil, headers: {}) + pattern = { headers: { 'Authorization' => 'Bearer dummy_token' } } + pattern[:query] = query if query + stub_request(method, "#{MAILERLITE_API_URL}#{path}") + .with(**pattern) { |req| req.body == body && req.headers['Idempotency-Key'] == key } + .to_return(status: status, body: response.to_json, headers: { 'Content-Type' => 'application/json' }.merge(headers)) + end + + def decoded(response) + JSON.parse(response.body.to_s) + end + + def invalid_ids + [ + ['', MailerLite::EmptyIdError], [nil, MailerLite::EmptyIdError], + ['123/html', MailerLite::InvalidIdError], ['123%2Fhtml', MailerLite::InvalidIdError], + ["123\n", MailerLite::InvalidIdError], ['²', MailerLite::InvalidIdError], ['١٢', MailerLite::InvalidIdError], + [-5, MailerLite::InvalidIdError], [(+"12\xFF").force_encoding('UTF-8'), MailerLite::InvalidIdError], + [true, TypeError], [1.5, TypeError] + ] + end + + def expect_invalid_ids(name) + invalid_ids.each do |value, error| + expect { yield value }.to raise_error(error, /`#{name}`/) + end + expect(a_request(:any, /.*/)).not_to have_been_made + end + + describe 'constants' do + it 'has the values of the API' do + expect(described_class::VERSION_CONFLICT).to eq 'version_conflict' + block_types = described_class::BlockType + expect([block_types::BLOCKQUOTE, block_types::BULLETED_LIST, block_types::BUTTON, block_types::CODE, + block_types::DIVIDER, block_types::HEADING, block_types::IMAGE, block_types::NUMBERED_LIST, + block_types::PARAGRAPH, block_types::SOCIAL_ICON, block_types::TITLE, block_types::VIDEO]) + .to eq %w[blockquote bulleted_list button code divider heading image numbered_list paragraph social_icon title video] + positions = described_class::BlockPosition + expect([positions::AT_START, positions::AT_END, positions::BEFORE, positions::AFTER]).to eq %w[start end before after] + modes = described_class::BrandMode + expect([modes::ACCOUNT, modes::TEMPLATE, modes::CUSTOM]).to eq %w[account template custom] + end + end + + describe '#get' do + it 'gets the email' do + stub = stub_api(:get, '/emails/123', response: load_fixture('email')) + + response = emails.get('123') + + expect(stub).to have_been_requested + expect(response).to be_a(HTTP::Response) + expect(response.code).to eq 200 + data = decoded(response) + expect(data['etag']).to eq '42' + expect(data['data']['id']).to eq '123' + expect(data['data']['type']).to eq 'builder_inline_email' + expect(data['data']['emailable_type']).to eq 'campaigns' + expect(data['data']['settings']['brand']['mode']).to eq 'account' + expect(data['data']['settings']['footer']['show_preferences']).to be(false) + expect(data['data']['settings']['footer']['social_links'][0]['link_id']).to eq 7 + expect(data['data']['blocks'][0]['editor_content']['attrs']['textAlign']).to eq 'left' + expect(data['data']['blocks'][1]['children'][0]['id']).to eq '3' + end + + it 'accepts an Integer ID' do + stub = stub_api(:get, '/emails/123', response: load_fixture('email')) + + emails.get(123) + + expect(stub).to have_been_requested + end + + it 'returns the error response and does not raise' do + stub_api(:get, '/emails/123', status: 404, response: { message: 'Resource not found.' }) + + response = emails.get('123') + + expect(response).to be_a(HTTP::Response) + expect(response.code).to eq 404 + expect(response.api_error.api_message).to eq 'Resource not found.' + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.get(id) } + end + end + + describe '#get_html' do + it 'gets the HTML of the email' do + stub = stub_api(:get, '/emails/123/html', response: load_fixture('email_html')) + + response = emails.get_html('123') + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['data']['html']).to eq '

Hello

' + expect(data['etag']).to eq '42' + end + + it 'returns a 503 with an HTML body and does not raise' do + stub_request(:get, "#{MAILERLITE_API_URL}/emails/123/html") + .to_return(status: 503, body: 'Service Unavailable', headers: { 'Content-Type' => 'text/html' }) + + response = emails.get_html('123') + + expect(response.code).to eq 503 + expect(response.api_error.status).to eq 503 + expect(response.api_error.api_message).to be_nil + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.get_html(id) } + end + end + + describe '#get_block' do + it 'gets the block and its placement' do + stub = stub_api(:get, '/emails/123/blocks/57', response: load_fixture('email_block')) + + response = emails.get_block(email_id: '123', block_id: 57) + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['etag']).to eq '43' + expect(data['data']['id']).to eq '57' + expect(data['data']['type']).to eq 'paragraph' + expect(data['data']['editor_content']['attrs']['textAlign']).to eq 'left' + expect(data['data']['placement']['after']).to eq '56' + expect(data['data']['placement']).to have_key('before') + expect(data['data']['placement']['before']).to be_nil + end + + it 'checks the IDs and sends no request' do + expect_invalid_ids('email_id') { |id| emails.get_block(email_id: id, block_id: '57') } + expect_invalid_ids('block_id') { |id| emails.get_block(email_id: '123', block_id: id) } + end + end + + describe '#create_block' do + let(:content) { { attrs: { textAlign: 'center' }, content: [{ type: 'text', text: 'Hi' }] } } + + it 'inserts the block with the placement and the etag' do + body = '{"type":"paragraph","editor_content":{"attrs":{"textAlign":"center"},"content":[{"type":"text","text":"Hi"}]},' \ + '"placement":{"position":"after","block_id":57},"etag":"42"}' + stub = stub_api(:post, '/emails/123/blocks', body: body, status: 201, response: load_fixture('email_block_created')) + placement = { position: described_class::BlockPosition::AFTER, block_id: 57 } + + response = emails.create_block(email_id: '123', etag: '42', type: described_class::BlockType::PARAGRAPH, + editor_content: content, placement: placement) + + expect(stub).to have_been_requested + expect(response.code).to eq 201 + data = decoded(response) + expect(data['etag']).to eq '43' + expect(data['data']['id']).to eq '58' + expect(data['data']['editor_content']['attrs']['textAlign']).to eq 'center' + expect(data['data']['placement']['after']).to eq '57' + expect(placement).to eq(position: 'after', block_id: 57) + end + + it 'sends no placement without a placement, and accepts empty content' do + stub = stub_api(:post, '/emails/123/blocks', body: '{"type":"divider","editor_content":{},"etag":"42"}', + status: 201, response: load_fixture('email_block_created')) + + emails.create_block(email_id: 123, etag: '42', type: 'divider', editor_content: {}) + + expect(stub).to have_been_requested + end + + it 'returns a version conflict with the code and the current etag' do + stub_api(:post, '/emails/123/blocks', body: '{"type":"divider","editor_content":{},"etag":"41"}', status: 409, + response: { message: 'The email was changed.', code: 'version_conflict', etag: '42' }) + + response = emails.create_block(email_id: '123', etag: '41', type: 'divider', editor_content: {}) + + expect(response.code).to eq 409 + expect(response.api_error.status).to eq 409 + expect(response.api_error.code).to eq described_class::VERSION_CONFLICT + expect(response.api_error.etag).to eq '42' + end + + it 'returns the field errors of a 422' do + stub_api(:post, '/emails/123/blocks', body: '{"type":"title","editor_content":{},"etag":"42"}', status: 422, + response: { message: 'The selected type is invalid.', errors: { type: ['The selected type is invalid.'] } }) + + response = emails.create_block(email_id: '123', etag: '42', type: 'title', editor_content: {}) + + expect(response.api_error.errors).to eq('type' => ['The selected type is invalid.']) + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.create_block(email_id: id, etag: '42', type: 'divider', editor_content: {}) } + end + + it 'sends an after placement without a block_id as given, and returns the API error' do + stub = stub_api(:post, '/emails/123/blocks', body: '{"type":"divider","editor_content":{},"placement":{"position":"after"},"etag":"42"}', + status: 422, response: { message: 'Invalid.', errors: { 'placement.block_id' => ['Required.'] } }) + + response = emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: { position: 'after' }) + + expect(stub).to have_been_requested + expect(response.api_error.errors).to eq('placement.block_id' => ['Required.']) + end + + it 'sends the values that the API checks, and returns the API error' do + calls = { + '{"type":"divider","editor_content":{},"etag":""}' => -> { emails.create_block(email_id: '123', etag: '', type: 'divider', editor_content: {}) }, + '{"type":"paragraph","editor_content":{},"etag":"42"}' => -> { emails.create_block(email_id: '123', etag: '42', type: :paragraph, editor_content: {}) }, + '{"type":"divider","editor_content":null,"etag":"42"}' => -> { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: nil) }, + '{"type":"divider","editor_content":{},"placement":"end","etag":"42"}' => + -> { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, placement: 'end') } + } + calls.each do |body, call| + stub = stub_api(:post, '/emails/123/blocks', body: body, status: 422, response: { message: 'Invalid.' }) + expect(call.call.api_error.status).to eq 422 + expect(stub).to have_been_requested + end + end + end + + describe '#update_block' do + it 'sends a PATCH request with the content and the etag' do + body = '{"editor_content":{"content":[{"type":"text","text":"Hello again"}]},"etag":"43"}' + stub = stub_api(:patch, '/emails/123/blocks/57', body: body, response: load_fixture('email_block_updated')) + + response = emails.update_block(email_id: '123', block_id: '57', etag: '43', + editor_content: { content: [{ type: 'text', text: 'Hello again' }] }) + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['etag']).to eq '44' + expect(data['data']['editor_content']['content'][0]['text']).to eq 'Hello again' + expect(data['data']['placement']).to eq('after' => '56', 'before' => '58') + end + + it 'checks the IDs and sends no request' do + expect_invalid_ids('email_id') { |id| emails.update_block(email_id: id, block_id: '57', etag: '43', editor_content: {}) } + expect_invalid_ids('block_id') { |id| emails.update_block(email_id: '123', block_id: id, etag: '43', editor_content: {}) } + end + + it 'sends an empty etag and content that is not a Hash, and returns the API error' do + stub = stub_api(:patch, '/emails/123/blocks/57', body: '{"editor_content":[],"etag":""}', status: 422, response: { message: 'Invalid.' }) + + response = emails.update_block(email_id: '123', block_id: '57', etag: '', editor_content: []) + + expect(stub).to have_been_requested + expect(response.api_error.status).to eq 422 + end + end + + describe '#delete_block' do + it 'sends a DELETE request with the etag in the body, and returns the new etag' do + stub = stub_api(:delete, '/emails/123/blocks/57', body: '{"etag":"44"}', response: load_fixture('email_etag')) + + response = emails.delete_block(email_id: '123', block_id: '57', etag: '44') + + expect(stub).to have_been_requested + expect(response).to be_a(HTTP::Response) + expect(decoded(response)).to eq('etag' => '45') + end + + it 'checks the IDs and sends no request' do + expect_invalid_ids('email_id') { |id| emails.delete_block(email_id: id, block_id: '57', etag: '44') } + expect_invalid_ids('block_id') { |id| emails.delete_block(email_id: '123', block_id: id, etag: '44') } + end + + it 'sends a nil etag as null' do + stub = stub_api(:delete, '/emails/123/blocks/57', body: '{"etag":null}', status: 422, response: { message: 'Invalid.' }) + + emails.delete_block(email_id: '123', block_id: '57', etag: nil) + + expect(stub).to have_been_requested + end + end + + describe '#move_block' do + it 'sends the placement and the etag' do + stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"before","block_id":1},"etag":"45"}', + response: load_fixture('email_block_moved')) + + response = emails.move_block(email_id: '123', block_id: '57', etag: '45', + placement: { 'position' => described_class::BlockPosition::BEFORE, 'block_id' => 1 }) + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['etag']).to eq '46' + expect(data['data']['placement']).to have_key('after') + expect(data['data']['placement']['after']).to be_nil + expect(data['data']['placement']['before']).to eq '1' + end + + it 'sends a placement without a block_id' do + stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"start"},"etag":"45"}', + response: load_fixture('email_block_moved')) + + emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { position: described_class::BlockPosition::AT_START }) + + expect(stub).to have_been_requested + end + + it 'sends the block_id for the start and end positions' do + stub = stub_api(:post, '/emails/123/blocks/57/move', body: '{"placement":{"position":"start","block_id":"12"},"etag":"45"}', + response: load_fixture('email_block_moved')) + + emails.move_block(email_id: '123', block_id: '57', etag: '45', + placement: { position: described_class::BlockPosition::AT_START, block_id: '12' }) + + expect(stub).to have_been_requested + end + + it 'checks the IDs in the URL and sends no request' do + expect_invalid_ids('email_id') { |id| emails.move_block(email_id: id, block_id: '57', etag: '45', placement: { position: 'end' }) } + expect_invalid_ids('block_id') { |id| emails.move_block(email_id: '123', block_id: id, etag: '45', placement: { position: 'end' }) } + end + + it 'sends the placement and the etag as given, and returns the API error' do + calls = { + '{"placement":{"position":"after","block_id":"1/2"},"etag":"45"}' => + -> { emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { position: 'after', block_id: '1/2' }) }, + '{"placement":{"position":"before"},"etag":"45"}' => + -> { emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: { 'position' => 'before' }) }, + '{"placement":null,"etag":"45"}' => -> { emails.move_block(email_id: '123', block_id: '57', etag: '45', placement: nil) }, + '{"placement":{"position":"end"},"etag":""}' => -> { emails.move_block(email_id: '123', block_id: '57', etag: '', placement: { position: 'end' }) } + } + calls.each do |body, call| + stub = stub_api(:post, '/emails/123/blocks/57/move', body: body, status: 422, response: { message: 'Invalid.' }) + expect(call.call.api_error.status).to eq 422 + expect(stub).to have_been_requested + end + end + end + + describe '#validate_block' do + it 'sends the block without an etag and returns the errors of the content' do + body = '{"type":"paragraph","editor_content":{"attrs":{"textAlign":"sideways"}},"placement":{"position":"end"}}' + result = { valid: false, errors: { 'editor_content.attrs.textAlign' => ['The value is not valid.'] }, + schema: { version: '2.73.2', hash: '0f3a9c' } } + stub = stub_api(:post, '/emails/blocks/validate', body: body, response: result) + + response = emails.validate_block(type: described_class::BlockType::PARAGRAPH, editor_content: { attrs: { textAlign: 'sideways' } }, + placement: { position: described_class::BlockPosition::AT_END }) + + expect(stub).to have_been_requested + expect(response.api_error).to be_nil + data = decoded(response) + expect(data['valid']).to be(false) + expect(data['errors']).to eq('editor_content.attrs.textAlign' => ['The value is not valid.']) + expect(data['schema']['version']).to eq '2.73.2' + end + + it 'returns an invalid result as a 200 response' do + stub = stub_api(:post, '/emails/blocks/validate', body: '{"type":"unknown","editor_content":{}}', + response: load_fixture('email_block_validation_invalid')) + + response = emails.validate_block(type: 'unknown', editor_content: {}) + + expect(stub).to have_been_requested + expect(response.api_error).to be_nil + data = decoded(response) + expect(data['valid']).to be(false) + expect(data['errors']).to eq('type' => ['The selected type is invalid.']) + end + + it 'sends a block that is not valid, and returns the result of the API' do + calls = { + '{"type":"divider","editor_content":{},"placement":{"position":"after"}}' => + -> { emails.validate_block(type: 'divider', editor_content: {}, placement: { position: 'after' }) }, + '{"type":"divider","editor_content":{},"placement":{"position":"before","block_id":"x"}}' => + -> { emails.validate_block(type: 'divider', editor_content: {}, placement: { position: 'before', block_id: 'x' }) }, + '{"type":null,"editor_content":{}}' => -> { emails.validate_block(type: nil, editor_content: {}) }, + '{"type":"divider","editor_content":"x"}' => -> { emails.validate_block(type: 'divider', editor_content: 'x') } + } + calls.each do |body, call| + stub = stub_api(:post, '/emails/blocks/validate', body: body, response: load_fixture('email_block_validation_invalid')) + expect(decoded(call.call)['valid']).to be(false) + expect(stub).to have_been_requested + end + end + end + + describe '#update_settings' do + it 'sends a PATCH request with only the keys of the caller and the etag' do + body = '{"brand":{"mode":"custom","background_color":"#f4f4f4"},"footer":{"company_name":""},"etag":"46"}' + stub = stub_api(:patch, '/emails/123/settings', body: body, response: load_fixture('email_settings')) + settings = { brand: { mode: described_class::BrandMode::CUSTOM, background_color: '#f4f4f4' }, footer: { company_name: '' } } + + response = emails.update_settings(email_id: '123', etag: '46', settings: settings) + + expect(stub).to have_been_requested + expect(settings).to eq(brand: { mode: 'custom', background_color: '#f4f4f4' }, footer: { company_name: '' }) + data = decoded(response) + expect(data['etag']).to eq '47' + expect(data['data']['brand']['mode']).to eq 'custom' + expect(data['data']['brand']['background_color']).to eq '#f4f4f4' + expect(data['data']['typography']['paragraph']['p1']['size']).to eq '16' + expect(data['rejected']['keys']).to eq ['footer.social_links[0].url'] + end + + it 'sends a nil value as null' do + stub = stub_api(:patch, '/emails/123/settings', body: '{"layout":{"alignment":null},"etag":"46"}', response: load_fixture('email_settings')) + + emails.update_settings(email_id: '123', etag: '46', settings: { 'layout' => { 'alignment' => nil } }) + + expect(stub).to have_been_requested + end + + it 'returns a version conflict' do + stub_api(:patch, '/emails/123/settings', body: '{"layout":{"alignment":"left"},"etag":"40"}', status: 409, + response: { message: 'The email was changed.', code: 'version_conflict', etag: '46' }) + + response = emails.update_settings(email_id: '123', etag: '40', settings: { layout: { alignment: 'left' } }) + + expect(response.api_error.code).to eq described_class::VERSION_CONFLICT + expect(response.api_error.etag).to eq '46' + end + + it 'checks the arguments and sends no request' do + expect_invalid_ids('email_id') { |id| emails.update_settings(email_id: id, etag: '46', settings: {}) } + expect { emails.update_settings(email_id: '123', etag: '46', settings: nil) }.to raise_error(TypeError, /`settings`/) + expect { emails.update_settings(email_id: '123', etag: '46', settings: { etag: '1' }) }.to raise_error(ArgumentError, /etag/) + expect { emails.update_settings(email_id: '123', etag: '46', settings: { 'etag' => '1' }) }.to raise_error(ArgumentError, /etag/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + + it 'sends an empty etag, and returns the API error' do + stub = stub_api(:patch, '/emails/123/settings', body: '{"etag":""}', status: 422, response: { message: 'Invalid.' }) + + response = emails.update_settings(email_id: '123', etag: '', settings: {}) + + expect(stub).to have_been_requested + expect(response.api_error.status).to eq 422 + end + end + + describe '#validate_settings' do + it 'sends the settings without an etag' do + stub = stub_api(:post, '/emails/123/settings/validate', body: '{"layout":{"width":"700"}}', response: load_fixture('email_settings_validation')) + + response = emails.validate_settings(email_id: '123', settings: { layout: { width: '700' } }) + + expect(stub).to have_been_requested + expect(response.api_error).to be_nil + data = decoded(response) + expect(data['valid']).to be(false) + expect(data['errors']).to eq('layout.width' => ['The layout.width field cannot be changed.']) + expect(data['rejected']['message']).to eq 'Some attributes were rejected.' + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.validate_settings(email_id: id, settings: {}) } + end + + it 'sends the settings as given, also with an etag key' do + calls = { + '{"etag":"1"}' => -> { emails.validate_settings(email_id: '123', settings: { etag: '1' }) }, + '"x"' => -> { emails.validate_settings(email_id: '123', settings: 'x') } + } + calls.each do |body, call| + stub = stub_api(:post, '/emails/123/settings/validate', body: body, response: load_fixture('email_settings_validation')) + expect(decoded(call.call)['valid']).to be(false) + expect(stub).to have_been_requested + end + end + end + + describe '#create_template' do + it 'sends the name and returns the template' do + stub = stub_api(:post, '/emails/123/templates', body: '{"name":"Newsletter"}', status: 201, response: load_fixture('email_template')) + + response = emails.create_template(email_id: '123', name: 'Newsletter') + + expect(stub).to have_been_requested + expect(response.code).to eq 201 + data = decoded(response) + expect(data['data']).to eq('id' => '789', 'name' => 'Newsletter', 'type' => 'email', 'created_at' => '2026-10-28 12:00:00') + expect(data).not_to have_key('etag') + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.create_template(email_id: id, name: 'Newsletter') } + end + + it 'sends a name that is not a String, and returns the API error' do + { '{"name":null}' => nil, '{"name":1}' => 1 }.each do |body, name| + stub = stub_api(:post, '/emails/123/templates', body: body, status: 422, response: { message: 'Invalid.' }) + expect(emails.create_template(email_id: '123', name: name).api_error.status).to eq 422 + expect(stub).to have_been_requested + end + end + end + + describe '#list_versions' do + it 'sends no query without options' do + stub = stub_api(:get, '/emails/123/versions', response: load_fixture('email_versions')) + + response = emails.list_versions('123') + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['data'].map { |version| version['id'] }).to eq %w[902 901] + expect(data['data'][0]['current']).to be(true) + expect(data['data'][1]['current']).to be(false) + expect(data['links']).to have_key('prev') + expect(data['links']['prev']).to be_nil + expect(data['meta']['total']).to eq 2 + end + + it 'sends the page and the limit' do + stub = stub_api(:get, '/emails/123/versions', query: { 'page' => '2', 'limit' => '10' }, response: load_fixture('email_versions')) + + emails.list_versions(123, page: 2, limit: 10) + + expect(stub).to have_been_requested + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.list_versions(id) } + end + end + + describe '#create_version' do + it 'sends no body and returns 201 for a new version' do + stub = stub_api(:post, '/emails/123/versions', body: '', status: 201, response: load_fixture('email_version')) + + response = emails.create_version('123') + + expect(stub).to have_been_requested + expect(response.code).to eq 201 + expect(decoded(response)['data']).to eq('id' => '903', 'created_at' => '2026-10-28 12:10:00', 'current' => true) + end + + it 'returns 200 for the last version when nothing changed' do + stub_api(:post, '/emails/123/versions', body: '', status: 200, response: load_fixture('email_version')) + + response = emails.create_version(123) + + expect(response.code).to eq 200 + expect(response.api_error).to be_nil + expect(decoded(response)['data']['id']).to eq '903' + end + + it 'checks the email ID and sends no request' do + expect_invalid_ids('email_id') { |id| emails.create_version(id) } + end + end + + describe '#restore_version' do + it 'sends the etag and returns the email' do + stub = stub_api(:post, '/emails/123/versions/901/restore', body: '{"etag":"47"}', response: load_fixture('email')) + + response = emails.restore_version(email_id: '123', version_id: 901, etag: '47') + + expect(stub).to have_been_requested + data = decoded(response) + expect(data['etag']).to eq '42' + expect(data['data']['id']).to eq '123' + expect(data['data']['blocks'].size).to eq 2 + end + + it 'checks the IDs and sends no request' do + expect_invalid_ids('email_id') { |id| emails.restore_version(email_id: id, version_id: '901', etag: '47') } + expect_invalid_ids('version_id') { |id| emails.restore_version(email_id: '123', version_id: id, etag: '47') } + end + + it 'sends an empty etag, and returns the API error' do + stub = stub_api(:post, '/emails/123/versions/901/restore', body: '{"etag":""}', status: 422, response: { message: 'Invalid.' }) + + response = emails.restore_version(email_id: '123', version_id: '901', etag: '') + + expect(stub).to have_been_requested + expect(response.api_error.status).to eq 422 + end + end + + describe 'idempotency keys' do + # Each item: the method, the path, the raw body, and a call with the key. + def writes + [ + [:post, '/emails/123/blocks', '{"type":"divider","editor_content":{},"etag":"42"}', + ->(key) { emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, idempotency_key: key) }], + [:patch, '/emails/123/blocks/57', '{"editor_content":{},"etag":"42"}', + ->(key) { emails.update_block(email_id: '123', block_id: '57', etag: '42', editor_content: {}, idempotency_key: key) }], + [:delete, '/emails/123/blocks/57', '{"etag":"42"}', + ->(key) { emails.delete_block(email_id: '123', block_id: '57', etag: '42', idempotency_key: key) }], + [:post, '/emails/123/blocks/57/move', '{"placement":{"position":"end"},"etag":"42"}', + ->(key) { emails.move_block(email_id: '123', block_id: '57', etag: '42', placement: { position: 'end' }, idempotency_key: key) }], + [:patch, '/emails/123/settings', '{"etag":"42"}', + ->(key) { emails.update_settings(email_id: '123', etag: '42', settings: {}, idempotency_key: key) }], + [:post, '/emails/123/templates', '{"name":"Newsletter"}', + ->(key) { emails.create_template(email_id: '123', name: 'Newsletter', idempotency_key: key) }], + [:post, '/emails/123/versions', '', + ->(key) { emails.create_version('123', idempotency_key: key) }], + [:post, '/emails/123/versions/901/restore', '{"etag":"42"}', + ->(key) { emails.restore_version(email_id: '123', version_id: '901', etag: '42', idempotency_key: key) }] + ] + end + + it 'sends the Idempotency-Key header on each write' do + writes.each do |method, path, body, call| + stub = stub_api(method, path, body: body, key: 'key-1', response: { etag: '43' }) + call.call('key-1') + expect(stub).to have_been_requested + end + end + + it 'sends no Idempotency-Key header without a key' do + writes.each do |method, path, body, call| + stub = stub_api(method, path, body: body, response: { etag: '43' }) + call.call(nil) + expect(stub).to have_been_requested + end + end + + it 'accepts a key with 255 characters' do + stub = stub_api(:post, '/emails/123/versions', key: 'k' * 255, status: 201, response: load_fixture('email_version')) + + emails.create_version('123', idempotency_key: 'k' * 255) + + expect(stub).to have_been_requested + end + + it 'sends the key as given, and returns the API error' do + writes.each do |method, path, body, call| + ['', ' k', 'k ', 'k' * 256].each do |key| + stub = stub_api(method, path, body: body, key: key, status: 400, response: { message: 'The idempotency key is not valid.' }) + expect(call.call(key).api_error.status).to eq 400 + expect(stub).to have_been_requested + end + end + end + + it 'shows a replay of a stored response' do + stub_api(:post, '/emails/123/blocks', body: '{"type":"divider","editor_content":{},"etag":"42"}', key: 'key-1', status: 201, + response: load_fixture('email_block_created'), headers: { 'Idempotent-Replayed' => 'True' }) + + response = emails.create_block(email_id: '123', etag: '42', type: 'divider', editor_content: {}, idempotency_key: 'key-1') + + expect(response.code).to eq 201 + expect(response.idempotent_replay?).to be(true) + expect(decoded(response)['data']['id']).to eq '58' + end + + it 'does not accept a key on the validate methods' do + expect { emails.validate_block(type: 'divider', editor_content: {}, idempotency_key: 'k') }.to raise_error(ArgumentError, /idempotency_key/) + expect { emails.validate_settings(email_id: '123', settings: {}, idempotency_key: 'k') }.to raise_error(ArgumentError, /idempotency_key/) + end + end +end diff --git a/spec/files_rspec.rb b/spec/files_rspec.rb new file mode 100644 index 0000000..aa200f9 --- /dev/null +++ b/spec/files_rspec.rb @@ -0,0 +1,90 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::Files do + include_context 'with the dummy API token' + + let(:files) { described_class.new(client: MailerLite::Client.new) } + let(:url) { "#{MAILERLITE_API_URL}/files" } + + def stub_files(query: nil, status: 200, response: load_fixture('files')) + stub = stub_request(:get, url).with(headers: { 'Authorization' => 'Bearer dummy_token' }) { |req| req.body == '' } + stub = stub.with(query: query) if query + stub.to_return(status: status, body: response.to_json, headers: { 'Content-Type' => 'application/json' }) + end + + # WebMock normalizes the URI (for example `+` becomes `%20`), so keep the raw URI that http.rb sends. + def capture_raw_uris + uris = [] + allow_any_instance_of(HTTP::Client).to receive(:perform).and_wrap_original do |method, request, options| + uris << request.uri.to_s + method.call(request, options) + end + uris + end + + it 'has the constants of the API' do + expect([described_class::FileType::IMAGE, described_class::FileType::PDF, described_class::FileType::EPUB]).to eq %w[image pdf epub] + sorts = described_class::FileSort + expect([sorts::CREATED_AT, sorts::CREATED_AT_DESC, sorts::NAME, sorts::NAME_DESC, sorts::SIZE, sorts::SIZE_DESC]) + .to eq %w[created_at -created_at name -name size -size] + end + + describe '#list' do + it 'sends no query without arguments' do + uris = capture_raw_uris + stub = stub_files + + response = files.list + + expect(stub).to have_been_requested + expect(uris).to eq [url] + data = JSON.parse(response.body.to_s) + expect(data['data'].map { |file| file['name'] }).to eq ['summer sale banner.png', 'summer sale terms.pdf'] + expect(data['data'][0]['width']).to eq 1200 + expect(data['data'][1]).to have_key('width') + expect(data['data'][1]['width']).to be_nil + expect(data['data'][1]['height']).to be_nil + expect(data['links']).to have_key('next') + expect(data['links']['next']).to be_nil + end + + it 'sends the filter, the sort and the pages, and encodes a space as +' do + uris = capture_raw_uris + stub = stub_files(query: { 'filter[name]' => 'summer sale', 'filter[type]' => 'image', 'sort' => '-size', 'page' => '1', 'limit' => '25' }) + + files.list(filter: { name: 'summer sale', type: described_class::FileType::IMAGE }, sort: described_class::FileSort::SIZE_DESC, page: 1, limit: 25) + + expect(stub).to have_been_requested + expect(uris).to eq ["#{url}?filter%5Bname%5D=summer+sale&filter%5Btype%5D=image&sort=-size&page=1&limit=25"] + end + + it 'drops a nil filter value and keeps an empty one' do + uris = capture_raw_uris + stub_files(query: { 'filter[type]' => '' }) + + files.list(filter: { name: nil, type: '' }) + + expect(uris).to eq ["#{url}?filter%5Btype%5D="] + end + + it 'returns the 422 of a file type that is not valid' do + stub_files(query: { 'filter[type]' => 'video' }, status: 422, + response: { message: 'The selected filter.type is invalid.', errors: { 'filter.type' => ['The selected filter.type is invalid.'] } }) + + response = files.list(filter: { type: 'video' }) + + expect(response.code).to eq 422 + expect(response.api_error.errors).to eq('filter.type' => ['The selected filter.type is invalid.']) + end + + it 'checks the filter and sends no request' do + expect { files.list(filter: 'image') }.to raise_error(TypeError, /`filter`/) + expect(a_request(:any, /.*/)).not_to have_been_made + end + end +end diff --git a/spec/fixtures/brand_styles.json b/spec/fixtures/brand_styles.json new file mode 100644 index 0000000..dab5ce3 --- /dev/null +++ b/spec/fixtures/brand_styles.json @@ -0,0 +1,50 @@ +{ + "data": { + "brand": { + "identifier": "account", + "name": "Brand styles", + "font_family": "Inter, sans-serif", + "primary_color": "#2cb191", + "secondary_color": "#1f2937", + "heading_color": "#111827", + "text_color": "#374151", + "border_color": "#e5e7eb", + "background_color": "#ffffff" + }, + "default": { + "identifier": "default-brand", + "name": "Default", + "font_family": "Inter, sans-serif", + "primary_color": "#09c269", + "secondary_color": "#000000", + "heading_color": "#000000", + "text_color": "#000000", + "border_color": "#e5e7eb", + "background_color": "#ffffff" + }, + "presets": [ + { + "identifier": "preset-business-casual", + "name": "Business casual", + "font_family": "Georgia, serif", + "primary_color": "#1d4ed8", + "secondary_color": "#1e3a8a", + "heading_color": "#0f172a", + "text_color": "#334155", + "border_color": "#cbd5e1", + "background_color": "#f8fafc" + }, + { + "identifier": "preset-retro", + "name": "Retro", + "font_family": "Courier New, monospace", + "primary_color": "#d97706", + "secondary_color": "#92400e", + "heading_color": "#451a03", + "text_color": "#78350f", + "border_color": "#fde68a", + "background_color": "#fffbeb" + } + ] + } +} diff --git a/spec/fixtures/campaign_simple_editor.json b/spec/fixtures/campaign_simple_editor.json new file mode 100644 index 0000000..d54f882 --- /dev/null +++ b/spec/fixtures/campaign_simple_editor.json @@ -0,0 +1,24 @@ +{ + "data": { + "id": "456", + "account_id": "1", + "name": "Simple editor campaign", + "type": "regular", + "status": "draft", + "default_email_id": "123", + "emails": [ + { + "id": "123", + "account_id": "1", + "emailable_id": "456", + "emailable_type": "campaigns", + "type": "builder_inline_email", + "from": "sender@example.com", + "from_name": "Sender", + "reply_to": "reply@example.com", + "subject": "Hello", + "is_designed": true + } + ] + } +} diff --git a/spec/fixtures/email.json b/spec/fixtures/email.json new file mode 100644 index 0000000..2762d5b --- /dev/null +++ b/spec/fixtures/email.json @@ -0,0 +1,81 @@ +{ + "data": { + "id": "123", + "type": "builder_inline_email", + "emailable_type": "campaigns", + "emailable_id": "456", + "settings": { + "brand": { + "mode": "account", + "font_family": "Inter, sans-serif", + "background_color": "#ffffff", + "text_color": "#000000", + "border_color": "#e5e7eb" + }, + "layout": {"width_mode": "default", "alignment": "center"}, + "typography": { + "link": {"color": "#2cb191"}, + "heading": { + "font_family": "Inter, sans-serif", + "font_weight": "700", + "line_height": "150%", + "letter_spacing": "0", + "h1": {"color": "#000000", "size": "32"}, + "h2": {"color": "#000000", "size": "24"}, + "h3": {"color": "#000000", "size": "20"} + }, + "paragraph": { + "font_family": "Inter, sans-serif", + "font_weight": "400", + "line_height": "150%", + "letter_spacing": "0", + "p1": {"color": "#000000", "size": "16"} + } + }, + "button": { + "font_family": "Inter, sans-serif", + "font_weight": "600", + "letter_spacing": "0", + "background_color": "#2cb191", + "text_color": "#ffffff", + "border_radius": "4" + }, + "footer": { + "show_preferences": false, + "company_name": { + "editor_content": { + "content": [{"type": "text", "text": "Acme", "marks": [{"type": "bold"}]}] + } + }, + "address": { + "editor_content": {"content": [{"text": "1 Main Street", "type": "text"}]} + }, + "info_text": { + "editor_content": {"content": [{"text": "You signed up on our website.", "type": "text"}]} + }, + "unsubscribe_text": "Unsubscribe", + "preferences_text": "Update your preferences", + "social_links": [ + {"url": "https://example.com", "type": "website", "label": "Website", "link_id": 7} + ] + } + }, + "blocks": [ + { + "id": "1", + "type": "paragraph", + "editor_content": { + "attrs": {"textAlign": "left"}, + "content": [{"text": "Hello", "type": "text"}] + } + }, + { + "id": "2", + "type": "bulleted_list", + "editor_content": {}, + "children": [{"id": "3", "type": "paragraph", "editor_content": {}}] + } + ] + }, + "etag": "42" +} diff --git a/spec/fixtures/email_block.json b/spec/fixtures/email_block.json new file mode 100644 index 0000000..df7d248 --- /dev/null +++ b/spec/fixtures/email_block.json @@ -0,0 +1,12 @@ +{ + "data": { + "id": "57", + "type": "paragraph", + "editor_content": { + "attrs": {"textAlign": "left"}, + "content": [{"text": "Hello", "type": "text"}] + }, + "placement": {"after": "56", "before": null} + }, + "etag": "43" +} diff --git a/spec/fixtures/email_block_created.json b/spec/fixtures/email_block_created.json new file mode 100644 index 0000000..7b52e03 --- /dev/null +++ b/spec/fixtures/email_block_created.json @@ -0,0 +1,12 @@ +{ + "data": { + "id": "58", + "type": "paragraph", + "editor_content": { + "attrs": {"textAlign": "center"}, + "content": [{"text": "Hi", "type": "text"}] + }, + "placement": {"after": "57", "before": null} + }, + "etag": "43" +} diff --git a/spec/fixtures/email_block_moved.json b/spec/fixtures/email_block_moved.json new file mode 100644 index 0000000..3041e81 --- /dev/null +++ b/spec/fixtures/email_block_moved.json @@ -0,0 +1,12 @@ +{ + "data": { + "id": "57", + "type": "paragraph", + "editor_content": { + "attrs": {"textAlign": "left"}, + "content": [{"text": "Hello", "type": "text"}] + }, + "placement": {"after": null, "before": "1"} + }, + "etag": "46" +} diff --git a/spec/fixtures/email_block_updated.json b/spec/fixtures/email_block_updated.json new file mode 100644 index 0000000..cb87a43 --- /dev/null +++ b/spec/fixtures/email_block_updated.json @@ -0,0 +1,9 @@ +{ + "data": { + "id": "57", + "type": "paragraph", + "editor_content": {"content": [{"text": "Hello again", "type": "text"}]}, + "placement": {"after": "56", "before": "58"} + }, + "etag": "44" +} diff --git a/spec/fixtures/email_block_validation_invalid.json b/spec/fixtures/email_block_validation_invalid.json new file mode 100644 index 0000000..c5c04fb --- /dev/null +++ b/spec/fixtures/email_block_validation_invalid.json @@ -0,0 +1,5 @@ +{ + "valid": false, + "errors": {"type": ["The selected type is invalid."]}, + "schema": {"version": "2.73.2", "hash": "0f3a9c"} +} diff --git a/spec/fixtures/email_etag.json b/spec/fixtures/email_etag.json new file mode 100644 index 0000000..730eaff --- /dev/null +++ b/spec/fixtures/email_etag.json @@ -0,0 +1 @@ +{"etag": "45"} diff --git a/spec/fixtures/email_html.json b/spec/fixtures/email_html.json new file mode 100644 index 0000000..d680c41 --- /dev/null +++ b/spec/fixtures/email_html.json @@ -0,0 +1 @@ +{"data": {"html": "

Hello

"}, "etag": "42"} diff --git a/spec/fixtures/email_settings.json b/spec/fixtures/email_settings.json new file mode 100644 index 0000000..b6193ec --- /dev/null +++ b/spec/fixtures/email_settings.json @@ -0,0 +1,111 @@ +{ + "data": { + "brand": { + "mode": "custom", + "font_family": "Inter, sans-serif", + "background_color": "#f4f4f4", + "text_color": "#000000", + "border_color": "#e5e7eb" + }, + "layout": { + "width_mode": "default", + "alignment": "center" + }, + "typography": { + "link": { + "color": "#2cb191" + }, + "heading": { + "font_family": "Inter, sans-serif", + "font_weight": "700", + "line_height": "150%", + "letter_spacing": "0", + "h1": { + "color": "#000000", + "size": "32" + }, + "h2": { + "color": "#000000", + "size": "24" + }, + "h3": { + "color": "#000000", + "size": "20" + } + }, + "paragraph": { + "font_family": "Inter, sans-serif", + "font_weight": "400", + "line_height": "150%", + "letter_spacing": "0", + "p1": { + "color": "#000000", + "size": "16" + } + } + }, + "button": { + "font_family": "Inter, sans-serif", + "font_weight": "600", + "letter_spacing": "0", + "background_color": "#2cb191", + "text_color": "#ffffff", + "border_radius": "4" + }, + "footer": { + "show_preferences": false, + "company_name": { + "editor_content": { + "content": [ + { + "type": "text", + "text": "Acme", + "marks": [ + { + "type": "bold" + } + ] + } + ] + } + }, + "address": { + "editor_content": { + "content": [ + { + "text": "1 Main Street", + "type": "text" + } + ] + } + }, + "info_text": { + "editor_content": { + "content": [ + { + "text": "You signed up on our website.", + "type": "text" + } + ] + } + }, + "unsubscribe_text": "Unsubscribe", + "preferences_text": "Update your preferences", + "social_links": [ + { + "url": "https://example.com", + "type": "website", + "label": "Website", + "link_id": 7 + } + ] + } + }, + "etag": "47", + "rejected": { + "message": "Some attributes were rejected.", + "keys": [ + "footer.social_links[0].url" + ] + } +} diff --git a/spec/fixtures/email_settings_validation.json b/spec/fixtures/email_settings_validation.json new file mode 100644 index 0000000..d1a571a --- /dev/null +++ b/spec/fixtures/email_settings_validation.json @@ -0,0 +1,9 @@ +{ + "valid": false, + "errors": {"layout.width": ["The layout.width field cannot be changed."]}, + "schema": {"version": "2.73.2", "hash": "0f3a9c"}, + "rejected": { + "message": "Some attributes were rejected.", + "keys": ["footer.social_links[0].url"] + } +} diff --git a/spec/fixtures/email_template.json b/spec/fixtures/email_template.json new file mode 100644 index 0000000..8f44cd4 --- /dev/null +++ b/spec/fixtures/email_template.json @@ -0,0 +1 @@ +{"data": {"id": "789", "name": "Newsletter", "type": "email", "created_at": "2026-10-28 12:00:00"}} diff --git a/spec/fixtures/email_version.json b/spec/fixtures/email_version.json new file mode 100644 index 0000000..8e0ef77 --- /dev/null +++ b/spec/fixtures/email_version.json @@ -0,0 +1 @@ +{"data": {"id": "903", "created_at": "2026-10-28 12:10:00", "current": true}} diff --git a/spec/fixtures/email_versions.json b/spec/fixtures/email_versions.json new file mode 100644 index 0000000..d1881d8 --- /dev/null +++ b/spec/fixtures/email_versions.json @@ -0,0 +1,26 @@ +{ + "data": [ + {"id": "902", "created_at": "2026-10-28 12:05:00", "current": true}, + {"id": "901", "created_at": "2026-10-28 12:00:00", "current": false} + ], + "links": { + "first": "https://connect.mailerlite.com/api/emails/123/versions?page=1", + "last": "https://connect.mailerlite.com/api/emails/123/versions?page=1", + "prev": null, + "next": null + }, + "meta": { + "current_page": 1, + "from": 1, + "last_page": 1, + "links": [ + {"url": null, "label": "« Previous", "page": null, "active": false}, + {"url": "https://connect.mailerlite.com/api/emails/123/versions?page=1", "label": "1", "page": 1, "active": true}, + {"url": null, "label": "Next »", "page": null, "active": false} + ], + "path": "https://connect.mailerlite.com/api/emails/123/versions", + "per_page": 25, + "to": 2, + "total": 2 + } +} diff --git a/spec/fixtures/files.json b/spec/fixtures/files.json new file mode 100644 index 0000000..4bf0846 --- /dev/null +++ b/spec/fixtures/files.json @@ -0,0 +1,44 @@ +{ + "data": [ + { + "id": "301", + "type": "image", + "name": "summer sale banner.png", + "url": "https://storage.example.com/files/summer-sale-banner.png", + "size": 48213, + "width": 1200, + "height": 600, + "created_at": "2026-10-20 09:30:00" + }, + { + "id": "302", + "type": "pdf", + "name": "summer sale terms.pdf", + "url": "https://storage.example.com/files/summer-sale-terms.pdf", + "size": 10240, + "width": null, + "height": null, + "created_at": "2026-10-21 10:00:00" + } + ], + "links": { + "first": "https://connect.mailerlite.com/api/files?page=1", + "last": "https://connect.mailerlite.com/api/files?page=1", + "prev": null, + "next": null + }, + "meta": { + "current_page": 1, + "from": 1, + "last_page": 1, + "links": [ + {"url": null, "label": "« Previous", "page": null, "active": false}, + {"url": "https://connect.mailerlite.com/api/files?page=1", "label": "1", "page": 1, "active": true}, + {"url": null, "label": "Next »", "page": null, "active": false} + ], + "path": "https://connect.mailerlite.com/api/files", + "per_page": 25, + "to": 2, + "total": 2 + } +} diff --git a/spec/params_rspec.rb b/spec/params_rspec.rb new file mode 100644 index 0000000..5f4c3be --- /dev/null +++ b/spec/params_rspec.rb @@ -0,0 +1,126 @@ +# frozen_string_literal: true + +require 'spec_helper' + +RSpec.describe MailerLite::Params do + describe 'error classes' do + it 'makes the client-side errors subclasses of ArgumentError' do + expect(MailerLite::EmptyIdError.ancestors).to include(ArgumentError) + expect(MailerLite::InvalidIdError.ancestors).to include(ArgumentError) + end + + it 'has a base error class for the SDK' do + expect(MailerLite::Error.ancestors).to include(StandardError) + end + end + + describe '.path_id' do + it 'returns a String of digits as it is' do + expect(described_class.path_id('123', 'email_id')).to eq '123' + end + + it 'returns an Integer as a String' do + expect(described_class.path_id(123, 'email_id')).to eq '123' + end + + it 'raises EmptyIdError for an empty String and for nil' do + expect { described_class.path_id('', 'email_id') }.to raise_error(MailerLite::EmptyIdError, /`email_id`/) + expect { described_class.path_id(nil, 'email_id') }.to raise_error(MailerLite::EmptyIdError, /`email_id`/) + end + + ['123/html', '123%2Fhtml', "123\n", ' 123', '²', '١٢', '1.5', '-5'].each do |value| + it "raises InvalidIdError for #{value.inspect}" do + expect { described_class.path_id(value, 'block_id') }.to raise_error(MailerLite::InvalidIdError, /`block_id`/) + end + end + + it 'raises InvalidIdError for a negative Integer' do + expect { described_class.path_id(-5, 'email_id') }.to raise_error(MailerLite::InvalidIdError) + end + + it 'raises InvalidIdError for a String with invalid bytes' do + value = (+"12\xFF").force_encoding('UTF-8') + expect { described_class.path_id(value, 'email_id') }.to raise_error(MailerLite::InvalidIdError) + end + + it 'raises InvalidIdError for a String in an encoding that is not ASCII compatible' do + expect { described_class.path_id('12'.encode('UTF-16LE'), 'email_id') }.to raise_error(MailerLite::InvalidIdError) + end + + [true, false, 1.5, :'123', ['1']].each do |value| + it "raises TypeError for #{value.inspect}" do + expect { described_class.path_id(value, 'email_id') }.to raise_error(TypeError, /`email_id`/) + end + end + end + + describe '.require_hash' do + it 'returns the Hash' do + value = { 'a' => 1 } + expect(described_class.require_hash(value, 'settings')).to be value + end + + [nil, 'image', [], 1].each do |value| + it "raises TypeError for #{value.inspect}" do + expect { described_class.require_hash(value, 'filter') }.to raise_error(TypeError, /`filter`/) + end + end + end + + describe '.settings' do + it 'returns the settings' do + settings = { brand: { mode: 'account' } } + expect(described_class.settings(settings)).to eq settings + end + + it 'raises ArgumentError for an etag key' do + expect { described_class.settings({ etag: '1' }) }.to raise_error(ArgumentError, /etag/) + expect { described_class.settings({ 'etag' => '1' }) }.to raise_error(ArgumentError, /etag/) + end + + it 'raises TypeError for settings that are not a Hash' do + expect { described_class.settings(nil) }.to raise_error(TypeError, /`settings`/) + end + end + + describe '.query' do + it 'returns an empty Hash with no values' do + expect(described_class.query).to eq({}) + end + + it 'adds a filter[key] value for each filter key' do + expect(described_class.query(filter: { name: 'summer sale', type: 'image' }, sort: '-size')) + .to eq('filter[name]' => 'summer sale', 'filter[type]' => 'image', 'sort' => '-size') + end + + it 'drops nil values, also in the filter' do + expect(described_class.query(filter: { name: nil, type: 'pdf' }, page: nil, limit: 10)) + .to eq('filter[type]' => 'pdf', 'limit' => 10) + end + + it 'keeps empty String values' do + expect(described_class.query(filter: { type: '' }, sort: '')) + .to eq('filter[type]' => '', 'sort' => '') + end + + it 'raises TypeError for a filter that is not a Hash' do + expect { described_class.query(filter: 'image') }.to raise_error(TypeError, /`filter`/) + end + end + + describe '.idempotency_headers' do + it 'returns no headers without a key' do + expect(described_class.idempotency_headers(nil)).to eq({}) + end + + it 'returns the header for a valid key' do + expect(described_class.idempotency_headers('key-1')).to eq('Idempotency-Key' => 'key-1') + end + + ['', 'a' * 256, 'é', ' k', 'k ', 1].each do |key| + it "returns the header with the key as given for #{key.inspect[0, 20]}" do + expect(described_class.idempotency_headers(key)).to eq('Idempotency-Key' => key) + end + end + end +end diff --git a/spec/request_rspec.rb b/spec/request_rspec.rb new file mode 100644 index 0000000..ce6c0f2 --- /dev/null +++ b/spec/request_rspec.rb @@ -0,0 +1,139 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' +require 'json' +require_relative 'support/json_fixture' + +RSpec.describe MailerLite::Request do + include_context 'with the dummy API token' + + let(:client) { MailerLite::Client.new } + let(:api) { MAILERLITE_API_URL } + + # WebMock normalizes the URI (for example `+` becomes `%20`), so keep the raw URI that http.rb sends. + def capture_raw_uris + uris = [] + allow_any_instance_of(HTTP::Client).to receive(:perform).and_wrap_original do |method, request, options| + uris << request.uri.to_s + method.call(request, options) + end + uris + end + + it 'sends a PATCH request with the JSON body' do + stub = stub_request(:patch, "#{api}/emails/1/settings") + .with { |req| req.body == '{"layout":{"alignment":"left"},"etag":"42"}' } + .to_return(status: 200, body: '{}') + + described_class.call(client, :patch, '/emails/1/settings', json: { 'layout' => { 'alignment' => 'left' }, 'etag' => '42' }) + + expect(stub).to have_been_requested + end + + it 'sends a DELETE request with the JSON body' do + stub = stub_request(:delete, "#{api}/emails/1/blocks/2") + .with { |req| req.body == '{"etag":"42"}' } + .to_return(status: 200, body: '{"etag":"43"}') + + described_class.call(client, :delete, '/emails/1/blocks/2', json: { 'etag' => '42' }) + + expect(stub).to have_been_requested + end + + it 'sends no body, not null, when there is no body' do + stub = stub_request(:post, "#{api}/emails/1/versions") + .with { |req| req.body == '' } + .to_return(status: 201, body: '{}') + + described_class.call(client, :post, '/emails/1/versions') + + expect(stub).to have_been_requested + end + + it 'sends the query and encodes a space as +' do + uris = capture_raw_uris + stub = stub_request(:get, "#{api}/files") + .with(query: { 'filter[name]' => 'summer sale', 'filter[type]' => '', 'page' => '2' }) + .to_return(status: 200, body: '{}') + + described_class.call(client, :get, '/files', query: { 'filter[name]' => 'summer sale', 'filter[type]' => '', 'page' => 2 }) + + expect(stub).to have_been_requested + expect(uris).to eq ["#{api}/files?filter%5Bname%5D=summer+sale&filter%5Btype%5D=&page=2"] + end + + it 'sends no query for an empty query' do + uris = capture_raw_uris + stub_request(:get, "#{api}/emails/1/versions").to_return(status: 200, body: '{}') + + described_class.call(client, :get, '/emails/1/versions', query: {}) + + expect(uris).to eq ["#{api}/emails/1/versions"] + end + + it 'sends the Authorization header and no Idempotency-Key header without a key' do + stub = stub_request(:post, "#{api}/emails/1/versions") + .with(headers: { 'Authorization' => 'Bearer dummy_token' }) + .with { |req| !req.headers.key?('Idempotency-Key') } + .to_return(status: 201, body: '{}') + + described_class.call(client, :post, '/emails/1/versions') + + expect(stub).to have_been_requested + end + + it 'sends the Idempotency-Key header with a key' do + stub = stub_request(:post, "#{api}/emails/1/versions") + .with(headers: { 'Idempotency-Key' => 'key-1' }) + .to_return(status: 201, body: '{}') + + described_class.call(client, :post, '/emails/1/versions', idempotency_key: 'key-1') + + expect(stub).to have_been_requested + end + + it 'sends a key with a space at the end as given' do + stub = stub_request(:post, "#{api}/emails/1/versions") + .with { |req| req.headers['Idempotency-Key'] == 'a b ' } + .to_return(status: 400, body: '{"message":"The idempotency key is not valid."}') + + response = described_class.call(client, :post, '/emails/1/versions', idempotency_key: 'a b ') + + expect(stub).to have_been_requested + expect(response.api_error.status).to eq 400 + end + + it 'returns the HTTP::Response with the ApiResponse methods' do + stub_request(:get, "#{api}/emails/1").to_return(status: 409, body: '{"message":"Conflict.","code":"version_conflict","etag":"9"}') + + response = described_class.call(client, :get, '/emails/1') + + expect(response).to be_a(HTTP::Response) + expect(response.code).to eq 409 + expect(response.api_error.etag).to eq '9' + expect(response.idempotent_replay?).to be(false) + end + + it 'reads the base URL when the request runs' do + original = MAILERLITE_API_URL + Object.send(:remove_const, :MAILERLITE_API_URL) + Object.const_set(:MAILERLITE_API_URL, 'http://api.example.com/api') + stub = stub_request(:get, 'http://api.example.com/api/emails/1').to_return(status: 200, body: '{}') + + described_class.call(client, :get, '/emails/1') + + expect(stub).to have_been_requested + ensure + Object.send(:remove_const, :MAILERLITE_API_URL) + Object.const_set(:MAILERLITE_API_URL, original) + end + + it 'does not change the Hashes of the caller' do + body = { 'etag' => '42' }.freeze + query = { 'page' => 1 }.freeze + stub_request(:delete, "#{api}/emails/1/blocks/2?page=1").to_return(status: 200, body: '{}') + + expect { described_class.call(client, :delete, '/emails/1/blocks/2', json: body, query: query) }.not_to raise_error + end +end diff --git a/spec/support/json_fixture.rb b/spec/support/json_fixture.rb new file mode 100644 index 0000000..45b5368 --- /dev/null +++ b/spec/support/json_fixture.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +require 'json' + +# Reads the JSON fixtures in `spec/fixtures` for the specs that use WebMock. +module JsonFixture + FIXTURE_DIR = File.expand_path('../fixtures', __dir__) + + def load_fixture(name) + JSON.parse(File.read(File.join(FIXTURE_DIR, "#{name}.json"))) + end +end + +if defined?(RSpec) + RSpec.configure { |config| config.include JsonFixture } + + # The specs do not depend on the token in the shell. + RSpec.shared_context 'with the dummy API token' do + around do |example| + old_token = ENV.fetch('MAILERLITE_API_TOKEN', nil) + ENV['MAILERLITE_API_TOKEN'] = 'dummy_token' + example.run + ensure + ENV['MAILERLITE_API_TOKEN'] = old_token + end + end +end