Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ dist
.env
.env.*
*.log
package-lock.json

/src/generated/prisma
/.idea
Expand Down
30 changes: 1 addition & 29 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,9 @@ API gateway, usage metering, and billing services for the Callora API marketplac

## Vault repository behavior

<<<<<<< HEAD
Endpoint:

`GET /api/developers/analytics`

Authentication:

- Requires `x-user-id` header (developer identity for now).

Query params:

- `from` (required): ISO date/time
- `to` (required): ISO date/time
- `groupBy` (optional): `day | week | month` (default: `day`)
- `apiId` (optional): filters to one API (must belong to authenticated developer)
- `includeTop` (optional): set to `true` to include `topEndpoints` and anonymized `topUsers`
=======
- Enforces one vault per user per network.
- `balanceSnapshot` is stored in smallest units using non-negative integer `bigint` values.
- `findByUserId` is network-aware and returns the vault for a specific user/network pair.
>>>>>>> main

## Local setup

Expand All @@ -52,9 +34,9 @@ Query params:
npm install
npm run dev
```
<<<<<<< HEAD

3. API base: `http://localhost:3000`

### Docker Setup

You can run the entire stack (API and PostgreSQL) locally using Docker Compose:
Expand All @@ -63,10 +45,6 @@ You can run the entire stack (API and PostgreSQL) locally using Docker Compose:
docker compose up --build
```
The API will be available at http://localhost:3000, and the PostgreSQL database will be mapped to local port 5432.
=======

3. API base: [http://localhost:3000](http://localhost:3000). Example: [http://localhost:3000/api/health](http://localhost:3000/api/health).
>>>>>>> main

## Scripts

Expand Down Expand Up @@ -102,12 +80,6 @@ callora-backend/

## Environment

<<<<<<< HEAD
- `PORT` — HTTP port (default: 3000). Optional for local dev.

This repo is part of [Callora](https://github.com/your-org/callora). Frontend: `callora-frontend`. Contracts: `callora-contracts`.
=======
- `PORT` - HTTP port (default: 3000). Optional for local dev.

This repo is part of [Callora](https://github.com/your-org/callora). Frontend: `callora-frontend`. Contracts: `callora-contracts`.
>>>>>>> main
45 changes: 5 additions & 40 deletions jest.config.cjs
Original file line number Diff line number Diff line change
@@ -1,55 +1,20 @@
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/?(*.)+(spec|test).ts'],
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
testMatch: ['**/?(*.)+(spec|test).ts'],
extensionsToTreatAsEsm: ['.ts'],
transform: {
'^.+\\.ts$': ['ts-jest', { useESM: true, tsconfig: 'tsconfig.json' }]
}
export default {
preset: 'ts-jest/presets/default-esm',
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
testMatch: ['**/?(*.)+(spec|test).ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
},
transform: {
'^.+\\.ts$': [
'^.+\\.tsx?$': [
'ts-jest',
{
useESM: false,
tsconfig: {
module: 'commonjs',
moduleResolution: 'node',
isolatedModules: true,
},
useESM: true,
tsconfig: 'tsconfig.jest.json',
diagnostics: { ignoreCodes: [151002] },
},
],
},
};
'^.+\\.tsx?$': ['ts-jest', {
useESM: true,
tsconfig: {
module: 'ESNext',
moduleResolution: 'Bundler',
},
}],
},
collectCoverageFrom: [
'src/**/*.ts',
'!src/index.ts',
],
coverageThreshold: {
global: {
lines: 95,
functions: 95,
branches: 95,
statements: 95,
},
},
testMatch: ['**/tests/integration/**/*.test.ts'],
};
11 changes: 5 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@
"db:migrate": "drizzle-kit migrate",
"db:studio": "drizzle-kit studio",
"typecheck": "tsc --noEmit",
"test": "node --import tsx --test \"src/**/*.test.ts\"",
"test:unit": "node --import tsx --test \"src/**/*.test.ts\"",
"test:integration": "node --import tsx --test \"tests/integration/**/*.test.ts\"",
"test:coverage": "node --import tsx --test --experimental-test-coverage \"src/**/*.test.ts\" \"tests/integration/**/*.test.ts\"",
"test": "node --import tsx --experimental-test-module-mocks --test \"src/**/*.test.ts\"",
"test:unit": "node --import tsx --experimental-test-module-mocks --test \"src/**/*.test.ts\"",
"test:integration": "NODE_OPTIONS='--experimental-vm-modules' jest",
"test:coverage": "node --import tsx --experimental-test-module-mocks --experimental-test-coverage --test \"src/**/*.test.ts\"",
"test:all": "npm run test:unit && npm run test:integration",
"test": "node --import tsx --test $(find src -name '*.test.ts')",
"test:coverage": "node --import tsx --test --experimental-test-coverage $(find src -name '*.test.ts')",
"validate:issue-9": "node scripts/validate-issue-9.mjs"
},
"dependencies": {
Expand Down Expand Up @@ -62,6 +60,7 @@
"pg-mem": "^3.0.13",
"prisma": "^7.4.1",
"supertest": "^7.2.2",
"ts-jest": "^29.4.6",
"tsx": "^4.7.0",
"typescript": "^5.9.3",
"typescript-eslint": "^8.56.1"
Expand Down
196 changes: 195 additions & 1 deletion src/app.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import test, { mock } from 'node:test';
import request from 'supertest';

import { createApp } from './app.js';
Expand All @@ -9,6 +9,15 @@ import type { ApiRepository, ApiListFilters } from './repositories/apiRepository
import type { Developer } from './db/schema.js';
import type { DeveloperRepository } from './repositories/developerRepository.js';
import { InMemoryApiRepository } from './repositories/apiRepository.js';
// Mock better-sqlite3 before any module that transitively imports it is loaded.
// This allows unit tests for app.ts to run without a compiled native binding.
await mock.module('better-sqlite3', {
defaultExport: class MockDatabase {
prepare() { return { get: () => null }; }
exec() {}
close() {}
},
});

const seedRepository = () =>
new InMemoryUsageEventsRepository([
Expand Down Expand Up @@ -441,3 +450,188 @@ test('GET /api/apis/:id returns api with empty endpoints list', async () => {
assert.equal(res.body.name, 'Empty API');
assert.deepEqual(res.body.endpoints, []);
});

// ---------------------------------------------------------------------------
// POST /api/developers/apis — publish a new API
// ---------------------------------------------------------------------------

const mockDeveloper = { id: 42, user_id: 'dev-1', name: 'Alice', website: null, description: null, category: null, created_at: new Date(), updated_at: new Date() };

const validApiBody = {
name: 'My Weather API',
description: 'Real-time weather data',
base_url: 'https://api.weather.example.com',
category: 'weather',
status: 'draft',
endpoints: [
{
path: '/forecast',
method: 'GET',
price_per_call_usdc: '0.01',
description: 'Get forecast',
},
],
};

const makeApp = (hasDeveloper = true) =>
createApp({
usageEventsRepository: seedRepository(),
findDeveloperByUserId: async () => (hasDeveloper ? mockDeveloper : undefined),
createApiWithEndpoints: async (input) => ({
id: 1,
developer_id: input.developer_id,
name: input.name,
description: input.description ?? null,
base_url: input.base_url,
logo_url: null,
category: input.category ?? null,
status: input.status ?? 'draft',
created_at: new Date(),
updated_at: new Date(),
endpoints: input.endpoints.map((ep, idx) => ({
id: idx + 1,
api_id: 1,
path: ep.path,
method: ep.method,
price_per_call_usdc: ep.price_per_call_usdc,
description: ep.description ?? null,
created_at: new Date(),
updated_at: new Date(),
})),
}),
});

test('POST /api/developers/apis returns 401 when unauthenticated', async () => {
const app = makeApp();
const res = await request(app).post('/api/developers/apis').send(validApiBody);
assert.equal(res.status, 401);
assert.equal(res.body.code, 'UNAUTHORIZED');
});

test('POST /api/developers/apis returns 400 when name is missing', async () => {
const app = makeApp();
const { name: _n, ...body } = validApiBody;
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send(body);
assert.equal(res.status, 400);
assert.match(res.body.error, /name/i);
});

test('POST /api/developers/apis returns 400 when base_url is missing', async () => {
const app = makeApp();
const { base_url: _b, ...body } = validApiBody;
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send(body);
assert.equal(res.status, 400);
assert.match(res.body.error, /base_url/i);
});

test('POST /api/developers/apis returns 400 when base_url is not a valid URL', async () => {
const app = makeApp();
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send({ ...validApiBody, base_url: 'not-a-url' });
assert.equal(res.status, 400);
assert.match(res.body.error, /base_url/i);
});

test('POST /api/developers/apis returns 400 when status is invalid', async () => {
const app = makeApp();
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send({ ...validApiBody, status: 'published' });
assert.equal(res.status, 400);
assert.match(res.body.error, /status/i);
});

test('POST /api/developers/apis returns 400 when endpoints is not an array', async () => {
const app = makeApp();
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send({ ...validApiBody, endpoints: 'bad' });
assert.equal(res.status, 400);
assert.match(res.body.error, /endpoints/i);
});

test('POST /api/developers/apis returns 400 when an endpoint path does not start with /', async () => {
const app = makeApp();
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send({
...validApiBody,
endpoints: [{ path: 'no-slash', method: 'GET', price_per_call_usdc: '0.01' }],
});
assert.equal(res.status, 400);
assert.match(res.body.error, /path/i);
});

test('POST /api/developers/apis returns 400 when an endpoint method is invalid', async () => {
const app = makeApp();
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send({
...validApiBody,
endpoints: [{ path: '/data', method: 'FETCH', price_per_call_usdc: '0.01' }],
});
assert.equal(res.status, 400);
assert.match(res.body.error, /method/i);
});

test('POST /api/developers/apis returns 400 when price_per_call_usdc is invalid', async () => {
const app = makeApp();
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send({
...validApiBody,
endpoints: [{ path: '/data', method: 'GET', price_per_call_usdc: 'free' }],
});
assert.equal(res.status, 400);
assert.match(res.body.error, /price_per_call_usdc/i);
});

test('POST /api/developers/apis returns 400 with DEVELOPER_NOT_FOUND when no developer profile', async () => {
const app = makeApp(false);
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send(validApiBody);
assert.equal(res.status, 400);
assert.equal(res.body.code, 'DEVELOPER_NOT_FOUND');
});

test('POST /api/developers/apis returns 201 with created API and endpoints', async () => {
const app = makeApp();
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send(validApiBody);
assert.equal(res.status, 201);
assert.equal(res.body.name, validApiBody.name);
assert.equal(res.body.base_url, validApiBody.base_url);
assert.equal(res.body.developer_id, mockDeveloper.id);
assert.ok(Array.isArray(res.body.endpoints));
assert.equal(res.body.endpoints.length, 1);
assert.equal(res.body.endpoints[0].path, '/forecast');
assert.equal(res.body.endpoints[0].method, 'GET');
});

test('POST /api/developers/apis returns 201 when endpoints array is empty', async () => {
const app = makeApp();
const res = await request(app)
.post('/api/developers/apis')
.set('x-user-id', 'dev-1')
.send({ ...validApiBody, endpoints: [] });
assert.equal(res.status, 201);
assert.ok(Array.isArray(res.body.endpoints));
assert.equal(res.body.endpoints.length, 0);
});
Loading
Loading