go-delivery-pricing
v0.1.1
Published
Framework-agnostic delivery pricing SDK for ecommerce checkout flows.
Downloads
382
Maintainers
Readme
Go Delivery Pricing
Framework-agnostic TypeScript SDK for ecommerce delivery pricing.
The package can collect quotes from configured Bolt, Yango, and Uber adapters plus an optional internal calculator. It selects the highest successful quote, applies a configurable markup, and then enforces a customer-facing minimum delivery price.
This is an ESM-only server-side package for Node.js >=20.
Install
npm install go-delivery-pricingMinimum Setup
External providers, Google Maps, and internal pricing are all optional. With this minimum
configuration, coordinate requests work and return minimumDeliveryPrice until a pricing source is
configured.
import { createDeliveryPricingClient } from "go-delivery-pricing";
const delivery = createDeliveryPricingClient({
pickupLocation: {
coordinates: { lat: 5.546861, lng: -0.2569154 },
},
currency: "GHS",
minimumDeliveryPrice: 25,
googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY,
});Internal Pricing
Internal pricing works without Bolt, Yango, Uber, or Google credentials when pickup and destination coordinates are supplied directly.
const delivery = createDeliveryPricingClient({
pickupLocation: {
coordinates: { lat: 5.546861, lng: -0.2569154 },
},
currency: "GHS",
minimumDeliveryPrice: 25,
internalDelivery: {
baseFee: 10,
perKmFee: 3,
includedDistanceKm: 3,
maximumFee: 150,
},
});
const price = await delivery.getDeliveryPrice({
coordinates: { lat: 5.6037, lng: -0.187 },
});The calculator resolves distance in this order:
distanceProvider, when configured.- Google Distance Matrix, when
googleMapsApiKeyis configured. - Haversine straight-line distance when both locations have coordinates.
Haversine distance is multiplied by haversineRoadFactor, which defaults to 1.25, to estimate
real road distance.
const delivery = createDeliveryPricingClient({
// Other configuration...
distanceProvider: {
async getDistance({ origin, destination }) {
return {
distanceMeters: await getRoadDistance(origin, destination),
};
},
},
});Internal rules behave as follows:
baseFeeis always included.includedDistanceKmis subtracted before applyingperKmFee.distanceBandsmatch against the full trip distance and usebaseFee + band.fee.minimumFeeandmaximumFeebound the internal quote.
Provider Adapters
Bolt, Yango, and Uber are optional because API access and endpoints vary by account and market. Configure only the adapters available to your application.
const delivery = createDeliveryPricingClient({
pickupLocation: {
coordinates: { lat: 5.546861, lng: -0.2569154 },
},
currency: "GHS",
minimumDeliveryPrice: 25,
providers: {
bolt: {
async getQuote(request) {
const amount = await fetchBoltPrice(request);
return {
source: "bolt",
amount,
currency: request.currency,
};
},
},
// yango and uber may be omitted
},
internalDelivery: {
baseFee: 10,
perKmFee: 3,
includedDistanceKm: 3,
maximumFee: 150,
},
});Every configured provider runs concurrently with internal pricing when it is enabled. Missing
providers appear in quotes with status: "skipped" and do not produce warnings.
Provider amounts use decimal currency units: 25.5 means GHS 25.50.
Price Selection
The SDK:
- Runs every configured external provider and the enabled internal calculator.
- Ignores skipped and failed results when selecting a price.
- Selects the highest successful quote.
- Calculates
selectedQuote.amount * markupMultiplier. - Applies
Math.max(minimumDeliveryPrice, calculatedAmount). - Rounds a successfully calculated checkout price up to a whole currency amount.
The default markupMultiplier is 1.5. For example, a selected quote of 50.25 produces 75.375,
which becomes a finalAmount of 76.
If no calculation succeeds, the result uses:
{
baseSource: "minimum",
baseAmount: minimumDeliveryPrice,
finalAmount: minimumDeliveryPrice,
usedFallback: true
}In this fallback case, minimumDeliveryPrice is returned exactly without applying markup or
whole-amount rounding.
A failed provider does not invalidate other successful quotes. warnings contains failed quote
messages only; absent or disabled sources are reported as skipped.
Location Search
Configure googleMapsApiKey to provide checkout address suggestions and Place ID resolution:
const matches = await delivery.searchLocations("East Legon");
const destination = await delivery.resolveLocation(matches[0].placeId);
const price = await delivery.getDeliveryPrice(destination);Call searchLocations(query) as the customer types, with normal debouncing. Call
resolveLocation(placeId) after selection, then call getDeliveryPrice(destination) before order
confirmation.
Google credentials are required for location search and Place ID resolution. They are not required
when the application supplies coordinates directly. Calling either Google helper without
googleMapsApiKey rejects with GoogleMapsError.
Next.js Setup
Keep the SDK and credentials in server-side Next.js code such as an App Router route handler.
// app/api/delivery-price/route.ts
import { createDeliveryPricingClient } from "go-delivery-pricing";
const delivery = createDeliveryPricingClient({
pickupLocation: {
coordinates: { lat: 5.546861, lng: -0.2569154 },
},
currency: "GHS",
minimumDeliveryPrice: 25,
googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY,
providers: {
// bolt: yourBoltAdapter,
},
internalDelivery: {
baseFee: 10,
perKmFee: 3,
includedDistanceKm: 3,
maximumFee: 150,
},
});
export async function POST(request: Request) {
const { destination } = await request.json();
const price = await delivery.getDeliveryPrice(destination);
return Response.json(price);
}Expose delivery.searchLocations(query) through a server route for checkout typeahead. Do not send
provider credentials to the client.
"use client";
import { useState } from "react";
export function CheckoutDeliveryPrice() {
const [amount, setAmount] = useState<number | null>(null);
async function loadPrice(destination: {
coordinates: { lat: number; lng: number };
}) {
const response = await fetch("/api/delivery-price", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ destination }),
});
if (!response.ok) throw new Error("Could not calculate delivery.");
const price = await response.json();
setAmount(price.finalAmount);
}
return (
<button
type="button"
onClick={() =>
loadPrice({ coordinates: { lat: 5.6037, lng: -0.187 } })
}
>
{amount === null ? "Calculate delivery" : `Delivery: GHS ${amount}`}
</button>
);
}React Setup
Browser-only React apps should call a backend endpoint built with Express, NestJS, Laravel, or another server framework. That backend imports this package and returns the price.
export async function fetchDeliveryPrice(destination: {
address?: string;
placeId?: string;
coordinates?: { lat: number; lng: number };
}) {
const response = await fetch("/api/delivery-price", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ destination }),
});
if (!response.ok) throw new Error("Could not load delivery price.");
return response.json();
}Do not import createDeliveryPricingClient into browser-only components. Doing so can expose Google
Maps keys, external provider credentials, and internal pricing rules.
Result Shape
Each known source is included with status: "success", "failed", or "skipped".
{
"currency": "GHS",
"baseSource": "internal",
"baseAmount": 37.5,
"markupMultiplier": 1.5,
"finalAmount": 57,
"usedFallback": false,
"quotes": [
{ "source": "bolt", "status": "skipped", "ok": false },
{ "source": "yango", "status": "skipped", "ok": false },
{ "source": "uber", "status": "skipped", "ok": false },
{
"source": "internal",
"status": "success",
"ok": true,
"quote": { "source": "internal", "amount": 37.5, "currency": "GHS" }
}
],
"warnings": []
}Scripts
npm run clean
npm run build
npm run typecheck
npm testPublishing
npm run build
npm run typecheck
npm test
npm --cache /private/tmp/go-delivery-npm-cache pack --dry-run
npm login
npm publish