forex-nepal
v0.0.1
Published
Simple, zero-dependency library providing Nepal Rastra Bank forex rates (NPR) with 30-minute in-memory caching.
Downloads
99
Maintainers
Readme
forex-nepal
Simple, zero-dependency library providing Nepal Rastra Bank forex rates (NPR) with 30-minute in-memory caching.
Install
npm install forex-nepal
Usage
forex-nepal
Simple, zero-dependency library that fetches forex rates from the Nepal Rastra Bank (NRB) and exposes a tiny, predictable API.
Key points:
- Zero runtime dependencies — works on Node.js 18+ (native
fetch). - In-memory cache with a 30 minute TTL.
- Minimal API:
getAllRates(),getRate(code),convert(amount, from, to).
Install
npm install forex-nepalUsage
This package works in Node.js (CommonJS or ESM), server frameworks (Express, Next.js, Nuxt) and client-side frameworks via bundlers. Below are concise examples.
Node (CommonJS)
const forex = require('forex-nepal');
(async () => {
const all = await forex.getAllRates();
console.log(all.USD);
// convert to NPR (explicit)
const npr = await forex.convert(100, 'USD', 'NPR');
console.log('100 USD → NPR:', npr);
// `to` defaults to NPR
const nprDefault = await forex.convert(50, 'USD');
console.log('50 USD → NPR (default):', nprDefault);
// convenience wrapper
const viaWrapper = await forex.convertToNPR(10, 'USD');
console.log('10 USD → NPR (wrapper):', viaWrapper);
})();Node (ESM)
If your project uses ESM (type: "module"), import like:
import * as forex from 'forex-nepal';
const usd = await forex.getRate('USD');Express (server)
Use the library inside request handlers. Keep in mind the package caches results in-memory per process.
const express = require('express');
const forex = require('forex-nepal');
const app = express();
app.get('/rate/:code', async (req, res) => {
const code = req.params.code;
const r = await forex.getRate(code);
if (!r) return res.status(404).send({ error: 'not found' });
res.send(r);
});
app.get('/convert', async (req, res) => {
const amount = Number(req.query.amount || 1);
const from = req.query.from || 'USD';
const to = req.query.to || 'NPR';
try {
const out = await forex.convert(amount, from, to);
res.send({ amount, from, to, result: out });
} catch (err) {
res.status(400).send({ error: String(err) });
}
});
app.listen(3000);Next.js / React (server-side and client-side)
Server-side usage (API routes or getServerSideProps) works as in Node.
Client-side in Next.js: the package relies on fetch to call NRB. Modern browsers support fetch — but avoid calling the module directly from purely static pages if you need SSR cache sharing.
Example API route (Next.js):
// pages/api/convert.js
import * as forex from 'forex-nepal';
export default async function handler(req, res) {
const { amount = 1, from = 'USD', to = 'NPR' } = req.query;
try {
const result = await forex.convert(Number(amount), from, to);
res.status(200).json({ result });
} catch (err) {
res.status(400).json({ error: String(err) });
}
}Vue 3 (client) / Nuxt
In a Vue 3 app with a bundler (Vite/Webpack) import the package and call from components. Prefer calling from server-side endpoints or use composables to avoid repeated fetches per component mount.
Example Vue 3 component (setup):
<script setup>
import { ref } from 'vue';
import * as forex from 'forex-nepal';
const rate = ref(null);
const load = async () => {
rate.value = await forex.getRate('USD');
};
load();
</script>
<template>
<div v-if="rate">USD: {{ rate.name }} — Buy: {{ rate.buy }}</div>
</template>For Nuxt (server-side): use the library inside server routes or server-side composables; SSR will run the module on the server where fetch is available (Node 18+ or polyfilled).
Browser / CDN usage
This package is distributed as CommonJS from dist/ by default. For browser usage there are a few options:
- Use a bundler (Vite, Webpack, Rollup) and import from
forex-nepal— bundlers will include the module in your bundle. - Use ESM CDNs (recommended for demos):
https://cdn.skypack.dev/forex-nepalorhttps://esm.sh/forex-nepal— these services transform packages for browser use. - Use UNPKG/JSDelivr to fetch the package files directly (for example,
https://cdn.jsdelivr.net/npm/forex-nepal/dist/index.js), but note that CommonJS builds may not run directly in browsers without bundling or transformation.
CDNJS: to make the library available on cdnjs you need to submit a PR to the cdnjs/cdnjs repository adding the package manifest and host the built assets (UMD/standalone bundles). cdnjs requires a clear upstream source (GitHub) and a build that produces browser-friendly files (UMD). If you'd like, I can add a Rollup config and UMD build script to produce a dist/forex-nepal.umd.js suitable for cdnjs.
API
getAllRates()→ Promise<Record<string, Rate>> — returns normalized rates keyed by ISO3 code.getRate(code)→ Promise<Rate|null> — returns a single rate ornullwhen missing.convert(amount, from, to)→ Promise — convertsamountfromfromtotousing NRB buy/sell rates andunit.getAllRates()→ Promise<Record<string, Rate>> — returns normalized rates keyed by ISO3 code.getRate(code)→ Promise<Rate|null> — returns a single rate ornullwhen missing.convert(amount, from, to = 'NPR')→ Promise — convertsamountfromfromtotousing NRB buy/sell rates andunit. Thetoparameter defaults toNPRfor convenience.convertToNPR(amount, from)→ Promise — convenience wrapper that convertsamountfromfromto NPR.
Type Rate shape:
{
"name": "U.S. Dollar",
"unit": 1,
"buy": 144.78,
"sell": 145.38,
"date": "YYYY-MM-DD"
}Caching
Results are cached in-memory for 30 minutes per process. In serverless or multi-process environments each instance will cache independently.
Tests
Run the included unit tests (no external test deps):
npm testContributing
Feel free to open issues or PRs on GitHub: https://github.com/birajrai/forex-nepal
License
MIT — see LICENSE.
Notes
This package intentionally keeps the API tiny and dependency-free. For heavy production use consider adding shared caching (Redis) or request retries/timeouts depending on your environment.
Data source & attribution
- This library uses the official Nepal Rastra Bank (NRB) forex API: https://www.nrb.org.np/api/forex/v1/app-rate.
- All rate data is provided by the Nepal Rastra Bank. Please credit Nepal Rastra Bank when displaying or publishing rates retrieved via this library.
- Respect NRB usage policies and avoid excessive polling — this package includes a 30-minute in-memory cache to reduce requests. If you need a higher-scale deployment, consider adding a shared cache (Redis) and obey any terms of service from the NRB website.
