npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

price-to-exchange-rate-update

v1.1.6

Published

A TypeScript/Node.js module for updating product prices stored in an SQL and NoSQL database based on exchange rate changes

Downloads

912

Readme

Price to Exchange Rate Update

A TypeScript/Node.js module for updating product prices based on exchange rate changes.

Installation

npm install price-to-exchange-rate-update

Features

  • Fetches latest exchange rates from a reliable API
  • Calculates price adjustments based on exchange rate changes
  • Supports custom database integration
  • TypeScript support with type definitions

Usage

Basic Setup

  1. Install the package:

    npm install price-to-exchange-rate-update
  2. Import and configure the updater in your project:

    // CommonJS
    const createExchangeRateUpdater = require("price-to-exchange-rate-update");
    
    // ES6 Modules
    import { createExchangeRateUpdater } from "price-to-exchange-rate-update";
    
    const updatePrices = createExchangeRateUpdater({
      fetchProducts: async () => {
        // Your logic to fetch products
      },
      updateProduct: async (id, data) => {
        // Your logic to update a product
      },
      apiKey: "your-exchange-rate-api-key",
      baseCurrency: "NGN",
      targetCurrency: "USD",
    });
    
    // Run the update
    updatePrices().then((result) => console.log(result));

Detailed Example with MongoDB

This example demonstrates how to use the package with a MongoDB database using Mongoose.

  1. Set up your database connection and model:

    // db.ts
    import mongoose from "mongoose";
    
    mongoose.connect("mongodb://localhost/your_database", {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    
    const ProductSchema = new mongoose.Schema({
      name: String,
      originalPrice: Number,
      discountPrice: Number,
    });
    
    const Product = mongoose.model("Product", ProductSchema);
    
    export { Product };
  2. Create functions to fetch and update products:

    // productOperations.ts
    import { Product } from "./db";
    
    export async function fetchProducts() {
      return await Product.find({});
    }
    
    export async function updateProduct(id: string, data: Partial<Product>) {
      await Product.findByIdAndUpdate(id, data);
    }
  3. Use the price-to-exchange-rate-update:

    • assign the currency in your database to the baseCurrency and targetCurrency in the createExchangeRateUpdater function
    // updatePrices.ts
    import { createExchangeRateUpdater } from "price-to-exchange-rate-update";
    import { fetchProducts, updateProduct } from "./productOperations";
    
    const updatePrices = createExchangeRateUpdater({
      fetchProducts,
      updateProduct,
      apiKey: "your-exchange-rate-api-key",
      baseCurrency: "NGN",
      targetCurrency: "USD",
    });
    
    async function runUpdate() {
      try {
        const result = await updatePrices();
        console.log(result);
      } catch (error) {
        console.error("Error updating prices:", error);
      }
    }
    
    runUpdate();
  4. Run the update script:

    ts-node updatePrices.ts

Important Note on API Key

WARNING: If you don't provide an API key, the module will use a default key, which may have usage limitations. It's strongly recommended to obtain your own API key from the Exchange Rate API service provider (https://www.exchangerate-api.com/).

To use your own API key, include it in the options when creating the exchange rate updater:

Important Note on Importing

This package supports both CommonJS and ES6 module systems. Please use the appropriate import syntax based on your project configuration:

For CommonJS (e.g., in Node.js without ES6 module support):

const createExchangeRateUpdater = require("price-to-exchange-rate-update");

For ES6 modules:

import createExchangeRateUpdater from "price-to-exchange-rate-update";

API Reference

createExchangeRateUpdater(options)

Creates an exchange rate updater function.

Parameters

  • options (Object):
    • fetchProducts (Function): Async function that returns an array of products.
    • updateProduct (Function): Async function to update a single product.
    • apiKey (String): Your Exchange Rate API key.
    • baseCurrency (String): The currency code to convert from (e.g., 'USD').
    • targetCurrency (String): The currency code to convert to (e.g., 'NGN').

Returns

  • (Function): An async function that when called, updates product prices based on the latest exchange rates.

TypeScript Support

This package is built with TypeScript and includes type definitions. You can import and use the module with full type support:

import { createExchangeRateUpdater } from "price-to-exchange-rate-update";

interface Product {
  id: string | number;
  originalPrice: number;
  discountPrice?: number | null;
}

const updatePrices = createExchangeRateUpdater({
  fetchProducts: async (): Promise<Product[]> => {
    // Your logic to fetch products
  },
  updateProduct: async (
    id: string | number,
    data: Partial<Product>
  ): Promise<void> => {
    // Your logic to update a product
  },
  apiKey: "your-exchange-rate-api-key",
  baseCurrency: "USD",
  targetCurrency: "NGN",
});

Product Model Structure

When using this module, ensure your product model adheres to the following structure:

interface Product {
  id: string | number;
  originalPrice: number;
  discountPrice?: number | null;
}

License

MIT