Skip to content

convert: what3words#652

Merged
carlbrugger merged 5 commits intomainfrom
convert/what3words
Oct 3, 2024
Merged

convert: what3words#652
carlbrugger merged 5 commits intomainfrom
convert/what3words

Conversation

@carlbrugger
Copy link
Contributor

Please explain how to summarize this PR for the Changelog:

Tell code reviewer how and what to test:

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

Walkthrough

The changes introduce the @flatfile/plugin-convert-what3words plugin, enabling the conversion of What3Words addresses into standard addresses and geographic coordinates. This version integrates the official What3Words JavaScript API, enhances functionality with TypeScript support, and includes configuration options for fields such as country and nearest place. Additionally, it improves error handling and type safety. A Rollup configuration file is added, and the documentation has been updated to reflect these changes.

Changes

File Change Summary
convert/what3words/CHANGELOG.md Updated to document changes in version 0.2.0, including API integration, field support, error handling, and dependency upgrades.
convert/what3words/README.md Introduced documentation for the new plugin, detailing configuration parameters, usage, and installation instructions.
convert/what3words/rollup.config.mjs Added a new Rollup configuration file with a basic setup for the build process.
convert/what3words/src/index.ts Introduced functionality for converting What3Words addresses, including a configuration interface and core conversion function.
flatfilers/sandbox/src/index.ts Removed ExcelExtractor and DelimiterExtractor plugins; added convertWhat3words plugin with specific sheet configuration.

Possibly related PRs

  • feat: add skipEmptyLines option #644: The changes in this PR introduce the skipEmptyLines option, which is relevant to the handling of data processing in the @flatfile/plugin-convert-what3words plugin, as it may also involve similar data extraction scenarios.
  • chore: update documentation #646: This PR updates documentation related to the @flatfile/plugin-delimiter-extractor and @flatfile/plugin-xlsx-extractor, which are relevant to the data handling improvements in the @flatfile/plugin-convert-what3words plugin.
  • Changeset for PR #654 #655: Although this PR focuses on patch updates across multiple plugins, it includes the plugin-delimiter-extractor, which is related to the data processing functionalities that may intersect with the changes made in the @flatfile/plugin-convert-what3words plugin.

Suggested reviewers

  • bangarang

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a31e636 and 8e5c5de.

📒 Files selected for processing (1)
  • .changeset/fast-trainers-fry.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/fast-trainers-fry.md

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (12)
convert/what3words/rollup.config.mjs (1)

1-5: Overall, the Rollup configuration looks good.

The file structure is correct and follows best practices for Rollup configuration files. It uses a custom configuration builder from '@flatfile/rollup-config', which suggests consistency with other Flatfile plugins.

To improve maintainability:

Consider adding a comment explaining the purpose of this configuration file and any specific requirements for the what3words plugin. This will help future developers understand the rationale behind using the default configuration or add custom options if needed.

Example:

// Rollup configuration for the what3words plugin
// Uses default configuration from @flatfile/rollup-config
// Add custom options here if specific build requirements arise for the what3words plugin
convert/what3words/CHANGELOG.md (1)

3-3: Consider adding version numbers in parentheses for consistency.

For better readability and consistency, consider adding the version number in parentheses for version 0.2.0, similar to how it's done for the initial release.

Here's a suggested change for line 3:

-## 0.2.0
+## 0.2.0 (Latest Release)

This change would make the format consistent with the initial release entry and provide additional clarity about the latest version.

Also applies to: 10-10

convert/what3words/README.md (3)

10-28: Adjust heading levels for consistency.

The parameters section provides clear and detailed information about each configuration option. However, the heading levels are inconsistent. Consider changing the parameter headings from h4 (####) to h3 (###) for better document structure.

Example fix for the first parameter:

-#### `config.what3wordsField` - `string`
+### `config.what3wordsField` - `string`

Apply this change to all parameter headings in this section.

🧰 Tools
🪛 Markdownlint

12-12: Expected: h3; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


30-46: Replace emphasis with proper headings for subsections.

The usage section provides valuable information about environment variables, installation, and import. To improve the document structure and readability, consider replacing the emphasized text with proper headings for each subsection.

Example fix:

-**Environment Variables**
+### Environment Variables

-**Install**
+### Install

-**Import**
+### Import

This change will create a clearer hierarchy in the document and improve navigation.

🧰 Tools
🪛 Markdownlint

32-32: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


38-38: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


43-43: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


48-60: Replace emphasis with a proper heading for the Listener.js section.

The Listener.js example effectively demonstrates how to configure and use the plugin. To improve the document structure, consider replacing the emphasized text with a proper heading.

Example fix:

-**Listener.js**
+### Listener.js

This change will maintain consistency with the document structure and improve navigation.

🧰 Tools
🪛 Markdownlint

48-48: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

convert/what3words/src/what3words.plugin.spec.ts (5)

17-24: LGTM: Well-structured configuration object

The configuration object is well-defined and includes all necessary fields for the what3words converter. This approach allows for easy customization of field names.

Consider extracting the 'test-api-key' into a constant at the top of the file for better maintainability:

const TEST_API_KEY = 'test-api-key';

// Then in the config object:
apiKey: TEST_API_KEY,

26-51: LGTM: Comprehensive test for valid What3Words address conversion

This test case thoroughly covers the happy path scenario for converting a valid What3Words address. It correctly mocks the API response and verifies that the record is updated with all expected fields.

Consider adding assertions to verify that the What3WordsApi constructor is called with the correct API key:

expect(mockWhat3WordsApi).toHaveBeenCalledWith({ apiKey: 'test-api-key' });

This ensures that the API is initialized correctly with the provided configuration.


53-68: LGTM: Good error handling test for invalid What3Words address

This test case effectively verifies the behavior when an invalid What3Words address is provided. It correctly mocks the API error and checks that the record fields remain undefined while an error message is added to the record.

To make the error checking more robust, consider asserting the exact number of errors:

expect(record.getErrors('w3w')).toHaveLength(1);

This ensures that only one error is added for the invalid address and prevents potential issues with multiple errors being added unintentionally.


70-81: LGTM: Good edge case handling for empty What3Words field

This test case effectively verifies the behavior when the What3Words field is empty. It correctly checks that the API is not called and that all fields remain undefined.

Consider adding an assertion to verify that no errors are added to the record in this case:

expect(record.getErrors()).toHaveLength(0);

This ensures that the converter doesn't add any unnecessary errors when the input field is empty.


1-81: Overall: Excellent test coverage with minor improvement suggestions

The test suite for the what3words converter is well-structured and comprehensive. It covers the main scenarios (valid conversion, invalid input, and empty input) and uses proper mocking and assertions. The tests follow good practices and provide solid coverage of the converter's functionality.

To further enhance the test suite, consider adding the following test cases:

  1. Test with partial configuration (e.g., missing some optional fields) to ensure the converter handles different configuration scenarios correctly.
  2. Test with multiple records to verify that the converter can handle batch processing if applicable.
  3. Test edge cases for the What3Words format (e.g., mixed case, leading/trailing spaces) to ensure robust input handling.

Example for testing with partial configuration:

it('should work with partial configuration', async () => {
  const partialConfig = {
    apiKey: 'test-api-key',
    what3wordsField: 'w3w',
    latField: 'lat',
    longField: 'long'
  };
  const record = new FlatfileRecord({ w3w: 'filled.count.soap' });
  const converter = what3wordsConverter(partialConfig);
  await converter(record);

  expect(record.get('lat')).toBeDefined();
  expect(record.get('long')).toBeDefined();
  expect(record.get('country')).toBeUndefined();
  expect(record.get('nearestPlace')).toBeUndefined();
});

These additional test cases will help ensure the robustness and flexibility of the what3words converter.

convert/what3words/src/index.ts (2)

38-38: Replace console logging with a structured logging approach

Using console.error and console.log for error handling and debugging is not recommended in production code as it can lead to unstructured logs and potential performance issues. Consider using a structured logging library or framework that integrates with your application's logging strategy.

Apply this diff to remove or replace console statements:

 // In getSecret function
 } catch (e) {
-  console.error(e, `Error fetching secret ${name}`)
+  // Handle the error appropriately, e.g., log using a logging library
   return undefined
 }

 // Inside the records loop
   try {
     const result = await w3wService.convertToCoordinates({ words })
-    console.log({ result })
     record.set(config.countryField, result.country)
     // ...
   } catch (error) {
-    console.log({ error })
     record.addError(
       config.what3wordsField,
       'Invalid What3Words address'
     )
   }

Also applies to: 67-67, 73-73


86-86: Ensure consistent export style

Currently, the convertWhat3words function is exported both as a named export and as the default export. This could lead to confusion when importing the module. Consider choosing one export style to maintain consistency.

Apply this diff to export only the default or named export:

Option 1: Export only the default export

-export function convertWhat3words(config: What3WordsConfig) {
+function convertWhat3words(config: What3WordsConfig) {
   // function implementation
 }
-export default convertWhat3words
+export default convertWhat3words

Option 2: Export only the named export

 export function convertWhat3words(config: What3WordsConfig) {
   // function implementation
 }
-export default convertWhat3words
🛑 Comments failed to post (4)
convert/what3words/src/index.ts (4)

66-71: ⚠️ Potential issue

Add null checks for API response fields to prevent runtime errors

When setting the fields from the result of w3wService.convertToCoordinates, there is an implicit assumption that result.country, result.nearestPlace, and result.coordinates are defined. If the API response is missing any of these fields, it could result in runtime errors. Consider adding null or undefined checks before setting these fields.

Apply this diff to add checks:

-record.set(config.countryField, result.country)
-record.set(config.nearestPlaceField, result.nearestPlace)
-record.set(config.latField, result.coordinates.lat)
-record.set(config.longField, result.coordinates.lng)
+if (result.country) {
+  record.set(config.countryField, result.country)
+}
+if (result.nearestPlace) {
+  record.set(config.nearestPlaceField, result.nearestPlace)
+}
+if (result.coordinates) {
+  record.set(config.latField, result.coordinates.lat)
+  record.set(config.longField, result.coordinates.lng)
+} else {
+  record.addError(config.what3wordsField, 'Unable to retrieve coordinates from What3Words')
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

            const result = await w3wService.convertToCoordinates({ words })
            console.log({ result })
            if (result.country) {
              record.set(config.countryField, result.country)
            }
            if (result.nearestPlace) {
              record.set(config.nearestPlaceField, result.nearestPlace)
            }
            if (result.coordinates) {
              record.set(config.latField, result.coordinates.lat)
              record.set(config.longField, result.coordinates.lng)
            } else {
              record.addError(config.what3wordsField, 'Unable to retrieve coordinates from What3Words')
            }

56-61: ⚠️ Potential issue

Handle missing What3Words API key to prevent runtime errors

The apiKey fetched by getSecret might be undefined if the secret is not found or an error occurs. Initializing the What3Words service with an undefined apiKey could lead to runtime errors when making API calls. Please add a check to ensure apiKey is defined before proceeding. If it is undefined, consider adding an error to all records or handling the error appropriately.

Apply this diff to add the check:

 const apiKey = await getSecret('W3W_API_KEY', environmentId, spaceId)
+if (!apiKey) {
+  // Handle the missing API key, e.g., add an error to records or throw an exception
+  const errorMessage = 'What3Words API key is missing. Please set the W3W_API_KEY secret.'
+  console.error(errorMessage)
+  records.forEach(record => record.addError(config.what3wordsField, errorMessage))
+  return
+}
 const transport: Transport = fetchTransport()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      const apiKey = await getSecret('W3W_API_KEY', environmentId, spaceId)
      if (!apiKey) {
        // Handle the missing API key, e.g., add an error to records or throw an exception
        const errorMessage = 'What3Words API key is missing. Please set the W3W_API_KEY secret.'
        console.error(errorMessage)
        records.forEach(record => record.addError(config.what3wordsField, errorMessage))
        return
      }
      const transport: Transport = fetchTransport()
      const w3wService: What3wordsService = what3words(apiKey, w3wConfig, {
        transport,
      })

62-81: ⚠️ Potential issue

Remove the premature return statement inside the record processing loop

The return record statement at line 80 is inside the loop iterating over records. This causes the function to exit after processing the first record, preventing the remaining records from being processed. To ensure all records are processed, remove the return statement from inside the loop.

Apply this diff to fix the issue:

         }
       }
-      return record
     }
+    return records
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      for (const record of records) {
        const words = record.get(config.what3wordsField) as string
        if (words) {
          try {
            const result = await w3wService.convertToCoordinates({ words })
            console.log({ result })
            record.set(config.countryField, result.country)
            record.set(config.nearestPlaceField, result.nearestPlace)
            record.set(config.latField, result.coordinates.lat)
            record.set(config.longField, result.coordinates.lng)
          } catch (error) {
            console.log({ error })
            record.addError(
              config.what3wordsField,
              'Invalid What3Words address'
            )
          }
        }
      }
    return records

25-41: 🛠️ Refactor suggestion

Improve error handling in getSecret function

Currently, if there's an error fetching the secret, the function logs the error and returns undefined. It might be more appropriate to throw an error or propagate it to the caller to handle it accordingly, especially if the secret is critical for the plugin's operation.

Consider modifying the function to throw an error:

 async function getSecret(
   name: string,
   environmentId?: string,
   spaceId?: string
 ): Promise<string> {
   try {
     const secrets = await api.secrets.list({ spaceId, environmentId })
     const secret = secrets.data.find((secret) => secret.name === name)
     if (!secret) {
-      return undefined
+      throw new Error(`Secret ${name} not found.`)
     }
     return secret.value
   } catch (e) {
-    console.error(e, `Error fetching secret ${name}`)
-    return undefined
+    throw new Error(`Error fetching secret ${name}: ${e.message}`)
   }
 }

And update the caller to handle the error:

 const apiKey = await getSecret('W3W_API_KEY', environmentId, spaceId)
+// No need to check for undefined apiKey here since getSecret will throw an error if not found
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

async function getSecret(
  name: string,
  environmentId?: string,
  spaceId?: string
): Promise<string> {
  try {
    const secrets = await api.secrets.list({ spaceId, environmentId })
    const secret = secrets.data.find((secret) => secret.name === name)
    if (!secret) {
      throw new Error(`Secret ${name} not found.`)
    }
    return secret.value
  } catch (e) {
    throw new Error(`Error fetching secret ${name}: ${e.message}`)
  }
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (4)
convert/what3words/README.md (4)

1-8: Improve formatting for better readability

The infocard section provides valuable information about the plugin. To enhance readability, consider the following suggestions:

  1. Add a heading for the plugin name.
  2. Use Markdown formatting instead of HTML comments for the infocard section.
  3. Use bold text for "Event Type:" instead of wrapping it in double asterisks.

Here's an example of how it could look:

# @flatfile/plugin-convert-what3words

## Overview

The `@flatfile/plugin-convert-what3words` plugin provides functionality to convert What3Words addresses to standard addresses and coordinates within Flatfile. It integrates with the official What3Words JavaScript API to perform the conversion and populate the user-specified fields with the results.

**Event Type:** `listener.on('commit:created')`

10-28: Adjust heading levels for consistency

The Parameters section provides clear explanations for each configuration option. However, the heading levels need adjustment to maintain proper hierarchy and address the Markdownlint warning (MD001). Here are the suggested changes:

  1. Change the "Parameters" heading to an h2 (##).
  2. Use h3 (###) for each parameter name instead of h4 (####).
  3. Consider adding a brief introduction to the Parameters section.

Example:

## Parameters

The following parameters can be used to configure the plugin:

### `config.what3wordsField` - `string`
The name of the field containing the What3Words address.

### `config.countryField` - `string`
The name of the field where the country code will be stored.

...

### `config.sheetSlug` - `string` - `default: **` - (optional)
The slug of the sheet to apply the converter to. If not provided, it will apply to all sheets with a `what3wordsField`.
🧰 Tools
🪛 Markdownlint

12-12: Expected: h3; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


30-60: Improve formatting in the Usage section

The Usage section provides valuable information on how to set up and use the plugin. To enhance readability and address the Markdownlint warnings (MD036), consider the following suggestions:

  1. Use proper heading levels instead of bold text for subsections.
  2. Add a brief introduction to the Usage section.
  3. Use consistent formatting for code blocks.

Here's an example of how it could look:

## Usage

Follow these steps to set up and use the @flatfile/plugin-convert-what3words plugin:

### Environment Variables

Add the following environment variable to your space:

- `W3W_API_KEY` - Your What3Words API key

### Installation

```bash
npm install @flatfile/plugin-convert-what3words

Importing the Plugin

import { convertWhat3words } from '@flatfile/plugin-convert-what3words'

Basic Configuration

Add the following to your Flatfile listener configuration:

listener.use(
  convertWhat3words({
    sheetSlug: 'locations',
    what3wordsField: 'what3words',
    countryField: 'country',
    nearestPlaceField: 'nearestPlace',
    latField: 'latitude',
    longField: 'longitude'
  })
)

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Markdownlint</summary><blockquote>

32-32: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

---

38-38: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

---

43-43: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

---

48-48: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

</blockquote></details>

</details>

---

`62-84`: **Enhance the Example Usage section**

The Example Usage section provides a good demonstration of how to implement the plugin. To make it even more helpful for users, consider the following suggestions:

1. Add a brief explanation of what the example does and why it's useful.
2. Comment on key parts of the code to explain their purpose.
3. Mention any prerequisites or assumptions made in the example.

Here's an improved version:

```markdown
## Example Usage

This example demonstrates how to set up the What3Words converter for the "locations" sheet, converting the "what3words" field to standard address components, latitude, and longitude.

```javascript
import { FlatfileListener } from '@flatfile/listener'
import convertWhat3words from '@flatfile/plugin-convert-what3words'

export default function (listener: FlatfileListener) {
  // Configure the What3Words converter plugin
  listener.use(
    convertWhat3words({
      sheetSlug: 'locations', // Apply the converter to the "locations" sheet
      what3wordsField: 'what3words', // Field containing the What3Words address
      countryField: 'country', // Field to store the country code
      nearestPlaceField: 'nearestPlace', // Field to store the nearest place name
      latField: 'latitude', // Field to store the latitude
      longField: 'longitude' // Field to store the longitude
    })
  )

  // Add other Flatfile listener configurations here
  // ...
}

Note: Ensure that you have set up the W3W_API_KEY environment variable before using this configuration.


</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**

<details>
<summary>📥 Commits</summary>

Files that changed from the base of the PR and between 41be670386e1c528fe99a442b222b2defe00e353 and ddb4044c47831321d8af69b5c305b3cb067292f5.

</details>

<details>
<summary>⛔ Files ignored due to path filters (3)</summary>

* `convert/what3words/package.json` is excluded by `!**/*.json`
* `package-lock.json` is excluded by `!**/package-lock.json`, `!**/*.json`
* `package.json` is excluded by `!**/*.json`

</details>

<details>
<summary>📒 Files selected for processing (5)</summary>

* convert/what3words/CHANGELOG.md (1 hunks)
* convert/what3words/README.md (1 hunks)
* convert/what3words/rollup.config.mjs (1 hunks)
* convert/what3words/src/index.ts (1 hunks)
* flatfilers/sandbox/src/index.ts (1 hunks)

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (3)</summary>

* convert/what3words/CHANGELOG.md
* convert/what3words/rollup.config.mjs
* convert/what3words/src/index.ts

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 Markdownlint</summary><blockquote>

<details>
<summary>convert/what3words/README.md</summary><blockquote>

12-12: Expected: h3; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)

---

32-32: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

---

38-38: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

---

43-43: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

---

48-48: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

</blockquote></details>

</blockquote></details>

</details>

<details>
<summary>🔇 Additional comments (3)</summary><blockquote>

<details>
<summary>flatfilers/sandbox/src/index.ts (3)</summary><blockquote>

`1-3`: **Imports are correctly included**

The necessary plugins are properly imported, ensuring that the required functionalities are available.

---

`7-13`: **Field mappings in `convertWhat3words` configuration are consistent**

The `convertWhat3words` plugin is correctly configured with the specified fields, matching the expected keys.

---

`17-60`: **Verify consistency between field keys and plugin configuration**

Ensure that the field keys defined in the sheet configuration match exactly with those specified in the `convertWhat3words` plugin configuration, particularly the `lat` and `long` fields.



Run the following script to confirm that all required fields are present and correctly named:

<details>
<summary>✅ Verification successful</summary>

<!-- [monologue]
[task verification_4/4]
[observations]
- The initial verification script confirmed that all required fields ('what3words', 'country', 'nearestPlace', 'lat', 'long') are present in the sheet configuration.
- The subsequent scripts extracted the `convertWhat3words` plugin configurations, both instances correctly reference the required fields.
- No discrepancies were found between the plugin configuration and the sheet's field keys.
- All required fields are consistently defined and used across configurations.

[analysis]
- The field keys in the `convertWhat3words` plugin configuration match exactly with those defined in the sheet configuration.
- Since no missing or mismatched fields were detected, the verification is successful.

[actions]
- Conclude the verification process by confirming that the field keys are consistent between the sheet configuration and the plugin configuration.
- Mark the verification as successful with the  tag.
-->
**Verified consistency between field keys and plugin configuration.**



</details>

<details>
<summary>🏁 Scripts executed</summary>

The following scripts were executed for the analysis:

Script:

```shell
#!/bin/bash
# Description: Verify that the field keys used in convertWhat3words match the fields defined in the sheet configuration.

# Expected: All fields in convertWhat3words configuration should be defined in the sheet.

# Extract field keys from sheet configuration in index.ts
field_keys=$(grep -oP "(?<=key: ')[^']+" flatfilers/sandbox/src/index.ts)

# Fields used in convertWhat3words configuration
required_fields=('what3words' 'country' 'nearestPlace' 'lat' 'long')

for field in "${required_fields[@]}"; do
  if ! echo "$field_keys" | grep -qx "$field"; then
    echo "Field '$field' used in convertWhat3words configuration is not defined in sheet configuration."
  fi
done

Length of output: 766


Script:

#!/bin/bash
# Description: Extract fields used in convertWhat3words plugin configuration.

# Search for convertWhat3words configuration block in index.ts and extract field keys
convert_fields=$(grep -A 10 "convertWhat3words" flatfilers/sandbox/src/index.ts | grep -oP "key: '\K[^']+")

echo "Fields used in convertWhat3words configuration:"
echo "$convert_fields"

Length of output: 231


Script:

#!/bin/bash
# Description: Extract full convertWhat3words plugin configuration from index.ts.

# Find the starting line number of the convertWhat3words configuration
start_line=$(grep -n "convertWhat3words" flatfilers/sandbox/src/index.ts | cut -d: -f1)

if [ -z "$start_line" ]; then
  echo "convertWhat3words plugin configuration not found in index.ts."
  exit 1
fi

# Define the number of lines to extract (adjust as needed)
lines_to_extract=30

# Extract the configuration block
convert_config=$(sed -n "${start_line},$((start_line + lines_to_extract))p" flatfilers/sandbox/src/index.ts)

echo "ConvertWhat3words plugin configuration:"
echo "$convert_config"

Length of output: 355


Script:

#!/bin/bash
# Description: Extract all convertWhat3words plugin configurations from index.ts.

# Find all starting line numbers of the convertWhat3words configuration
start_lines=$(grep -n "convertWhat3words" flatfilers/sandbox/src/index.ts | cut -d: -f1)

if [ -z "$start_lines" ]; then
  echo "convertWhat3words plugin configuration not found in index.ts."
  exit 1
fi

# Define the number of lines to extract for each configuration block
lines_to_extract=30

# Iterate over each starting line and extract the configuration block
echo "Extracted ConvertWhat3words plugin configurations:"

echo "$start_lines" | while read -r line; do
  echo "---- Configuration starting at line $line ----"
  sed -n "${line},$((line + lines_to_extract))p" flatfilers/sandbox/src/index.ts
  echo "---- End of Configuration ----"
done

Length of output: 2338

Comment on lines +42 to +50
key: 'lat',
type: 'number',
label: 'Latitude',
},
{
key: 'long',
type: 'number',
label: 'Longitude',
},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider using 'lng' instead of 'long' for longitude field key

The key long might be confused with the reserved word long in some programming contexts. It's common practice to use lng as the abbreviation for longitude.

Apply the following changes:

In the convertWhat3words configuration:

-      longField: 'long',
+      longField: 'lng',

In the configureSpace plugin under fields:

       {
-        key: 'long',
+        key: 'lng',
         type: 'number',
         label: 'Longitude',
       },

Committable suggestion was skipped due to low confidence.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
convert/what3words/README.md (2)

10-28: Adjust heading levels for consistency

The parameters section provides clear and detailed information about each configuration option. However, to improve the document structure and adhere to Markdown best practices, consider changing the heading levels:

Apply this change to all parameter headings:

-#### `config.what3wordsField` - `string`
+### `config.what3wordsField` - `string`

This will ensure a consistent and proper heading hierarchy throughout the document.

🧰 Tools
🪛 Markdownlint

12-12: Expected: h3; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


30-60: Use proper headings for subsections

The usage section provides comprehensive information on setting up and using the plugin. To improve the document structure and navigation:

Replace bold text with proper headings for subsections:

-**Environment Variables**
+### Environment Variables

-**Install**
+### Install

-**Import**
+### Import

-**Listener.js**
+### Listener.js

This change will enhance the document's structure and make it easier for users to navigate through different sections.

🧰 Tools
🪛 Markdownlint

32-32: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


38-38: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


43-43: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


48-48: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ddb4044 and d58684b.

⛔ Files ignored due to path filters (3)
  • convert/what3words/package.json is excluded by !**/*.json
  • package-lock.json is excluded by !**/package-lock.json, !**/*.json
  • package.json is excluded by !**/*.json
📒 Files selected for processing (5)
  • convert/what3words/CHANGELOG.md (1 hunks)
  • convert/what3words/README.md (1 hunks)
  • convert/what3words/rollup.config.mjs (1 hunks)
  • convert/what3words/src/index.ts (1 hunks)
  • flatfilers/sandbox/src/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • convert/what3words/CHANGELOG.md
  • convert/what3words/rollup.config.mjs
  • convert/what3words/src/index.ts
  • flatfilers/sandbox/src/index.ts
🧰 Additional context used
🪛 Markdownlint
convert/what3words/README.md

12-12: Expected: h3; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


32-32: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


38-38: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


43-43: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


48-48: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

🔇 Additional comments (2)
convert/what3words/README.md (2)

1-8: LGTM: Informative infocard section

The infocard section provides a clear and concise overview of the plugin's functionality and the event it listens to. This is helpful for users to quickly understand the plugin's purpose.


62-84: LGTM: Clear and informative example

The example usage section provides a comprehensive and well-structured demonstration of how to integrate the plugin into a Flatfile listener configuration. This will be very helpful for users looking to implement the plugin in their projects.

Comment on lines +1 to +84
<!-- START_INFOCARD -->

The `@flatfile/plugin-convert-what3words` plugin provides functionality to convert What3Words addresses to standard addresses and coordinates within Flatfile. It integrates with the official What3Words JavaScript API to perform the conversion and populate the user-specified fields with the results.

**Event Type:**
`listener.on('commit:created')`

<!-- END_INFOCARD -->

## Parameters

#### `config.what3wordsField` - `string`
The `what3wordsField` parameter is the name of the field containing the What3Words address.

#### `config.countryField` - `string`
The `countryField` parameter is the name of the field where the country code will be stored.

#### `config.nearestPlaceField` - `string`
The `nearestPlaceField` parameter is the name of the field where the nearest place name will be stored.

#### `config.latField` - `string`
The `latField` parameter is the name of the field where the latitude coordinate will be stored.

#### `config.longField` - `string`
The `longField` parameter is the name of the field where the longitude coordinate will be stored.

#### `config.sheetSlug` - `string` - `default: **` - (optional)
The `sheetSlug` parameter is the slug of the sheet to apply the converter to. If not provided, it will apply to all sheets with a `what3wordsField`.

## Usage

**Environment Variables**

Add the following environment variables to your space:

- `W3W_API_KEY` - Your What3Words API key

**Install**
```bash install
npm install @flatfile/plugin-convert-what3words
```

**Import**
```js
import { convertWhat3words } from '@flatfile/plugin-convert-what3words'
```

**Listener.js**
```js
listener.use(
convertWhat3words({
sheetSlug: 'locations',
what3wordsField: 'what3words',
countryField: 'country',
nearestPlaceField: 'nearestPlace',
latField: 'latitude',
longField: 'longitude'
})
)
```

### Example Usage

This example sets up the What3Words converter for the "locations" sheet, converting the "what3words" field to standard address, latitude, and longitude.

```javascript
import { FlatfileListener } from '@flatfile/listener'
import convertWhat3words from '@flatfile/plugin-convert-what3words'

export default function (listener: FlatfileListener) {
listener.use(
convertWhat3words({
sheetSlug: 'locations',
what3wordsField: 'what3words',
countryField: 'country',
nearestPlaceField: 'nearestPlace',
latField: 'latitude',
longField: 'longitude'
})
)

// ... rest of your Flatfile listener configuration
}
```
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance overall README structure and content

The README provides comprehensive information about the @flatfile/plugin-convert-what3words plugin. To further improve its structure and readability, consider the following suggestions:

  1. Add a table of contents at the beginning of the document for easy navigation.
  2. Include a "Features" section to highlight the key capabilities of the plugin.
  3. Add a "Requirements" section to clearly state any prerequisites (e.g., What3Words API key).
  4. Consider adding a "Troubleshooting" or "FAQ" section to address common issues or questions users might have.
  5. Include information about contributing to the plugin and how to report issues.
  6. Add a license section at the end of the README.

Here's a suggested structure:

# @flatfile/plugin-convert-what3words

## Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
- [Configuration](#configuration)
- [Example](#example)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)

## Overview
(existing content)

## Features
- Converts What3Words addresses to standard addresses and coordinates
- Integrates with the official What3Words JavaScript API
- Customizable field mapping
- ...

## Requirements
- Flatfile account
- What3Words API key

(rest of the sections)

## Contributing
(guidelines for contributing)

## License
(license information)

These changes will make the README more comprehensive and user-friendly, providing a better experience for developers looking to use or contribute to the plugin.

🧰 Tools
🪛 Markdownlint

12-12: Expected: h3; Actual: h4
Heading levels should only increment by one level at a time

(MD001, heading-increment)


32-32: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


38-38: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


43-43: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


48-48: null
Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8b6a47e and 14c0464.

📒 Files selected for processing (1)
  • .changeset/fast-trainers-fry.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
.changeset/fast-trainers-fry.md

[grammar] ~5-~5: The singular determiner ‘this’ may not agree with the plural noun ‘plugins’. Did you mean “these”?
Context: ...--- Introducing the What3Words plugin! This plugins take a What3Words location and ...

(THIS_NNS)

🔇 Additional comments (1)
.changeset/fast-trainers-fry.md (1)

1-3: LGTM: Metadata section is correctly formatted.

The metadata section correctly specifies a minor version bump for the '@flatfile/plugin-convert-what3words' plugin.

Co-Authored-By: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@carlbrugger carlbrugger merged commit d9ab4f2 into main Oct 3, 2024
@carlbrugger carlbrugger deleted the convert/what3words branch October 3, 2024 20:56
bangarang added a commit that referenced this pull request Oct 4, 2024
* convert: what3words

* Delete convert/what3words/CHANGELOG.md

* Update convert/what3words/src/index.ts

Co-authored-by: Alex Rock <hi@lxrck.com>

* Update index.ts

* Create fast-trainers-fry.md

Co-Authored-By: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: Alex Rock <hi@lxrck.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants