由 Opal W. 出售

Ghostfolio is a self-hostable wealth management web app built with NestJS and Angular that lets individuals track stocks, ETFs, and crypto across accounts with data-driven portfolio analytics.
This block provides the complete NestJS backend API for Ghostfolio, an open-source wealth management platform. It handles portfolio tracking, transaction management, authentication, data provider integration, and real-time caching via Redis. The target buyer is a developer embedding a self-hosted financial portfolio backend into an existing Node.js/TypeScript infrastructure.
app/ - NestJS application modules, controllers, and services organized by feature domainassets/ - Static assets served by the API (e.g., locale files)decorators/ - Custom NestJS parameter and method decoratorsenvironments/ - Environment-specific configuration objects (environment.ts, environment.prod.ts)events/ - NestJS EventEmitter event definitions and handlersguards/ - Auth guards (JWT, API key, roles)helper/ - Pure utility functions shared across modulesinterceptors/ - NestJS interceptors for response transformation and loggingmiddlewares/ - Express middleware (e.g., request logging)models/ - Shared model classes and DTOsservices/ - Singleton application-level services (data providers, Prisma, configuration)dependencies.ts - Imports dotenv and dotenv-expand for Docker/Prisma compatibilitymain.ts - Application entry point: bootstraps NestJS, configures CORS, versioning, Helmet, and global pipesnpm install @nestjs/common @nestjs/core @nestjs/config @nestjs/platform-express \
@nestjs/bull @nestjs/cache-manager @nestjs/event-emitter \
@bull-board/api @bull-board/express @bull-board/nestjs \
@prisma/client prisma \
@keyv/redis keyv \
cookie-parser helmet \
dotenv dotenv-expand \
class-validator class-transformer \
passport passport-jwt passport-google-oauth20 \
@nestjs/passport @nestjs/jwt \
bull ioredis \
date-fns @date-fns/utc \
@internationalized/number
npm install --save-dev @nestjs/cli @types/cookie-parser @types/passport-jwt \
@types/helmet @types/express typescript ts-node
A running PostgreSQL instance and a running Redis instance are required. Prisma migrations must be applied before first boot (). No iOS/Android native steps apply.
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript library / package completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 d651467732defbdd…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
npx prisma migrate deployCopy the contents of source/ into your project under apps/api/src/ (mirroring the Nx workspace layout) or into src/ for a standalone NestJS project.
Add path aliases in tsconfig.json so internal cross-library imports resolve:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@ghostfolio/common/*": ["libs/common/src/*"],
"@ghostfolio/api-client": ["libs/api-client/src/index.ts"]
},
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"module": "CommonJS",
"target": "ES2020"
}
}
.env file at the project root with required environment variables:# .env
DATABASE_URL="postgresql://user:password@localhost:5432/ghostfolio"
REDIS_HOST=localhost
REDIS_PORT=6379
JWT_SECRET=changeme
ACCESS_TOKEN_SALT=changeme
LOG_LEVELS='["log","warn","error"]'
NODE_ENV=production
npx prisma migrate deploy
npx prisma generate
npx ts-node -r tsconfig-paths/register src/main.ts
# or with the NestJS CLI:
nest start
The API listens on http://localhost:3333/api/v1 by default (port and host read from @ghostfolio/common/config constants DEFAULT_PORT / DEFAULT_HOST).
bootstrap (main.ts)async function bootstrap(): Promise<void>
The application entry point. Instantiates two NestJS apps — one to read ConfigService for log-level configuration, one as the actual NestExpressApplication. Applies cookie-parser, helmet, CORS, URI versioning with default version "1", and a global ValidationPipe. Call (or re-export) this only when running the API as a standalone process.
AppModule (app/app.module.ts)@Module({ imports: [...], controllers: [...], providers: [...] })
export class AppModule {}
Root NestJS module that wires every feature module (auth, account, portfolio, admin, symbol, etc.) together with global providers like ConfigModule and PrismaService. Import this when constructing a custom entry point or writing integration tests with Test.createTestingModule.
environment (environments/environment.ts)export const environment: { production: boolean; [key: string]: unknown }
Compile-time environment flags. The production boolean gates log-level defaults inside bootstrap. Reference this object inside services or interceptors to branch behavior between development and production builds.
Drop-in replacement for main.ts that forces debug logging regardless of env.
import { NestFactory } from '@nestjs/core';
import type { NestExpressApplication } from '@nestjs/platform-express';
import { ValidationPipe } from '@nestjs/common';
import { VersioningType } from '@nestjs/common';
import cookieParser from 'cookie-parser';
import helmet from 'helmet';
import { AppModule } from './app/app.module';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
logger: ['debug', 'error', 'log', 'verbose', 'warn']
});
app.use(cookieParser());
app.use(helmet());
app.enableCors();
app.enableVersioning({
defaultVersion: '1',
type: VersioningType.URI
});
app.setGlobalPrefix('api');
app.useGlobalPipes(
new ValidationPipe({ transform: true, whitelist: true })
);
await app.listen(3333, '0.0.0.0');
console.log('API running on http://localhost:3333/api/v1');
}
bootstrap();
Write an integration test that spins up the real module graph against a test database.
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication, ValidationPipe, VersioningType } from '@nestjs/common';
import { AppModule } from './app/app.module';
import * as request from 'supertest';
describe('Health endpoint', () => {
let app: INestApplication;
beforeAll(async () => {
const moduleRef: TestingModule = await Test.createTestingModule({
imports: [AppModule]
}).compile();
app = moduleRef.createNestApplication();
app.enableVersioning({ defaultVersion: '1', type: VersioningType.URI });
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ transform: true }));
await app.init();
});
it('GET /api/v1/health returns 200', () => {
return request(app.getHttpServer())
.get('/api/v1/health')
.expect(200);
});
afterAll(() => app.close());
});
In Dockerfile CMD scripts or Prisma config helpers, import dependencies.ts first so dotenv and dotenv-expand are registered before any database initialization.
// prisma-bootstrap.ts (runs before migrations in Docker entrypoint)
import '../src/dependencies'; // registers dotenv + dotenv-expand
import { execSync } from 'child_process';
execSync('npx prisma migrate deploy', { stdio: 'inherit' });
console.log('Migrations applied.');
main.ts - Entry point: creates the NestExpressApplication, wires global middleware, versioning, and starts the HTTP listener.dependencies.ts - Side-effect import of dotenv/dotenv-expand required by Prisma config inside Docker.app/app.module.ts - Root module; imports all feature modules and global providers.app/app.controller.ts - Catch-all and health-adjacent routes not owned by a specific feature module.app/auth/ - JWT, API key, Google OAuth, and OIDC strategy implementations plus the auth controller and service.app/account/ - Account CRUD controller and service; exposes CashDetailsInterface.app/account-balance/ - Dedicated module for account balance snapshots separate from transaction history.app/activities/ - Portfolio activity (transaction) ingestion, listing, and deletion.app/admin/ - Admin-only endpoints for system management; includes a queue/ sub-module exposing Bull queue dashboard.app/portfolio/ - Core portfolio analytics controller and service (performance, holdings, dividends).app/symbol/ - Asset symbol lookup and market data endpoints.app/import/ - Bulk transaction import endpoint.app/export/ - Transaction export endpoint.app/user/ - User profile management.app/info/ - Public instance info endpoint (version, features, subscription tiers).app/endpoints/ - Grouped endpoints for AI, API keys, assets, and data providers.services/ - Application-level singletons: PrismaService, data provider aggregation, caching.guards/ - AuthGuard variants for JWT and API key authentication.interceptors/ - Response shape normalization and performance logging.middlewares/ - Express-level request middleware (logging, locale detection).decorators/ - Custom decorators such as @Public() to bypass auth guards.models/ - Shared DTOs and value objects used across multiple modules.environments/ - environment.ts (dev) and environment.prod.ts (prod) flag objects.events/ - Event payload types for NestJS EventEmitter bus.helper/ - Stateless utility functions (date arithmetic, number formatting, etc.).assets/ - Static files (i18n, reference data) bundled with the API.emitDecoratorMetadata not enabled: NestJS dependency injection silently fails; set "emitDecoratorMetadata": true in tsconfig.json.DATABASE_URL: Prisma client throws at module init, not at query time; verify the env var is exported before nest start.@nestjs/cache-manager with @keyv/redis will crash the process; ensure Redis is healthy before starting the API or add a retry strategy in the cache module config.api combined with versioning produces /api/v1/...; routes registered without the prefix (Bull board, sitemap) must be explicitly excluded via setGlobalPrefix exclude option as shown in main.ts.LOG_LEVELS must be valid JSON: The bootstrap reads it with JSON.parse; a malformed string silently falls back to defaults but the try/catch swallows errors — always validate with JSON.parse locally first.npx prisma generate after every schema migration; stale clients cause runtime type errors that are hard to trace.I have purchased the Ghostfolio NestJS Backend API source block.
The source lives at `source/` relative to this file.
A complete integration guide is in `USAGE.md` (also in this directory).
The upstream package is `user@example.com`.
My existing project is a Node.js/TypeScript application. Please integrate
the Ghostfolio backend API into it step by step:
1. Read `USAGE.md` fully before writing any code.
2. Copy or reference `source/` into the correct location in my project
(explain the target path and why).
3. Update `tsconfig.json` with the required path aliases from `USAGE.md`.
4. Add all npm dependencies listed in `USAGE.md` § "Required dependencies".
5. Create or update `.env` with all variables from `USAGE.md` § "Project setup".
6. Wire the `AppModule` from `source/app/app.module.ts` into my entry point,
applying CORS, URI versioning (default "1"), global prefix "api", and
ValidationPipe exactly as shown in `USAGE.md`.
7. Apply Prisma migrations and generate the client.
8. Add a smoke-test (supertest) against GET /api/v1/health as shown in
`USAGE.md` § "Working examples".
9. Point out any conflicts with my existing code and suggest resolutions.
Do not invent modules or imports that are not present in `source/` or
documented in `USAGE.md`.
Ghostfolio is released under the GNU Affero General Public License v3.0 (AGPL-3.0). Any modifications to the source must be made available under the same license when deployed as a network service. See source/LICENSE if present, or refer to https://www.gnu.org/licenses/agpl-3.0.
Upstream project: https://github.com/ghostfolio/ghostfolio | npm: user@example.com.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费