synapse-recommendation
v0.1.5
Published
TypeScript client for the Recommenda recommendation API
Downloads
645
Maintainers
Readme
synapse-recommendation
TypeScript SDK for the Recommenda API — a recommendation engine built for second-hand marketplaces.
Recommenda tracks how users interact with products and other users, then computes personalised product and user recommendations using a hybrid scoring algorithm (content-based filtering, collaborative filtering, geo-proximity, and seller affinity).
This SDK provides typed methods for every API endpoint. It has zero runtime dependencies and uses the native fetch API.
Install
npm install synapse-recommendationQuick start
import { RecommendaClient } from "synapse-recommendation";
const client = new RecommendaClient({
baseUrl: "https://your-api-url.com",
apiKey: "sk_live_...",
});
// Register a product
await client.createProduct({
productId: "prod-123",
category: "electronics",
sellerId: "seller-456",
latitude: 51.5,
longitude: -0.1,
});
// Record a user viewing a product
await client.recordInteraction({
userId: "user-789",
productId: "prod-123",
type: "view",
});
// Get personalised recommendations
const { recommendations } = await client.getProductRecommendations({
userId: "user-789",
limit: 20,
});Authentication
Every environment has its own API keys. Pass the key when creating the client — it is sent as the X-Api-Key header on every request.
const client = new RecommendaClient({
baseUrl: "https://your-api-url.com",
apiKey: "sk_live_...",
});Admin operations (creating environments, managing API keys) use a separate master key:
import { RecommendaAdmin } from "synapse-recommendation";
const admin = new RecommendaAdmin({
baseUrl: "https://your-api-url.com",
adminKey: "your-admin-key",
});API reference
Products
Products represent items listed on your marketplace. Each product has a category, a seller, and a geographic location.
// Create a product
const product = await client.createProduct({
productId: "prod-123",
category: "electronics",
sellerId: "seller-456",
latitude: 51.5,
longitude: -0.1,
});
// Get a product by ID
const detail = await client.getProduct("prod-123");
// Update category or location
const updated = await client.updateProduct("prod-123", {
category: "phones",
});
// Delete a product
await client.deleteProduct("prod-123");Users
Users are created implicitly when they interact with products or other users. When a user deletes their account, call deleteUser to remove all their data — interactions, recommendations, and user-to-user interactions are all cleaned up. The user's products are marked as deleted.
await client.deleteUser("user-789");Product interactions
Interactions record how users engage with products. These drive the recommendation engine.
| Type | Weight | Removable |
|------|--------|-----------|
| view | 1 | No |
| favourite | 3 | Yes |
| purchase | 5 | No |
Purchases are immutable and automatically mark the product as sold.
// Record a view, favourite, or purchase
await client.recordInteraction({
userId: "user-789",
productId: "prod-123",
type: "favourite",
});
// Remove a favourite
await client.removeInteraction({
userId: "user-789",
productId: "prod-123",
type: "favourite",
});
// List a user's interactions (optionally filter by type)
const { interactions } = await client.getInteractions({
userId: "user-789",
type: "favourite",
limit: 20,
});User interactions
User interactions record how users engage with other users (e.g. viewing a seller's profile or favouriting a seller). These feed directly into user recommendations and boost the favourited seller's products in product recommendations.
| Type | Weight | Removable |
|------|--------|-----------|
| view | 1 | No |
| favourite | 3 | Yes |
// Record a profile view or favourite
await client.recordUserInteraction({
userId: "user-789",
targetUserId: "seller-456",
type: "favourite",
});
// Remove a user favourite
await client.removeUserInteraction({
userId: "user-789",
targetUserId: "seller-456",
type: "favourite",
});
// List a user's interactions with other users
const { interactions } = await client.getUserInteractions({
userId: "user-789",
type: "favourite",
limit: 20,
});Recommendations
Recommendations are precomputed and updated every 10 minutes. Requesting recommendations is a read operation — no computation happens at query time.
Product recommendations
Returns products scored and ranked for a specific user. Supports filtering by category, geo-radius, and token-based pagination.
Each recommendation includes a score (0-1), the reasons it was recommended (e.g. category_match, collaborative, geo_nearby, seller_affinity, recency), and the product's location.
const result = await client.getProductRecommendations({
userId: "user-789",
category: "electronics", // optional: filter by category
latitude: 51.5, // optional: enable distance filtering
longitude: -0.1,
radius: 25, // optional: radius in km (requires lat/lng)
limit: 20,
});
for (const rec of result.recommendations) {
console.log(rec.productId, rec.score, rec.reasons);
}
// Paginate — the token is self-contained, no need to resend query params
if (result.meta.nextPageToken) {
const page2 = await client.getProductRecommendations({
pageToken: result.meta.nextPageToken,
});
}User recommendations
Returns other users ranked by similarity — based on overlapping product taste, direct interactions, and geographic proximity.
Each recommendation includes sharedCategories (categories both users have interacted with) and activeListings (how many products the recommended user currently has listed).
const result = await client.getUserRecommendations({
userId: "user-789",
limit: 10,
});
for (const rec of result.recommendations) {
console.log(rec.userId, rec.score, rec.reasons, rec.activeListings);
}Environments and API keys
Environments provide multi-tenancy — each environment has its own isolated set of users, products, interactions, and recommendations.
import { RecommendaAdmin } from "synapse-recommendation";
const admin = new RecommendaAdmin({
baseUrl: "https://your-api-url.com",
adminKey: "your-admin-key",
});
// Create an environment (returns an initial API key)
const env = await admin.createEnvironment({ name: "production" });
console.log(env.environmentId, env.apiKey.key);
// List all environments
const { environments } = await admin.listEnvironments();
// Create additional API keys for an environment
const key = await admin.createApiKey(env.environmentId, {
label: "mobile-app",
});
// List keys
const { apiKeys } = await admin.listApiKeys(env.environmentId);
// Revoke a key
await admin.revokeApiKey(env.environmentId, key.id);Error handling
All API errors are thrown as RecommendaError with the HTTP status, an error code, and a message.
import { RecommendaError } from "synapse-recommendation";
try {
await client.getProduct("nonexistent");
} catch (err) {
if (err instanceof RecommendaError) {
console.log(err.status); // 404
console.log(err.code); // "NOT_FOUND"
console.log(err.message); // "Product not found"
}
}Common error codes:
| Status | Code | When |
|--------|------|------|
| 400 | BAD_REQUEST | Invalid input (missing fields, self-interaction) |
| 401 | UNAUTHORIZED | Missing or invalid API key |
| 404 | NOT_FOUND | Resource does not exist |
| 409 | CONFLICT | Product already sold or unavailable |
| 422 | VALIDATION_ERROR | Input fails schema validation |
Custom fetch
You can provide your own fetch implementation for use in environments without native fetch, or to add logging, retries, or custom headers:
const client = new RecommendaClient({
baseUrl: "https://your-api-url.com",
apiKey: "sk_live_...",
fetch: myCustomFetch,
});Requirements
- Node.js >= 18 (uses native
fetch) - Zero runtime dependencies
