Compare commits

..

31 Commits

Author SHA1 Message Date
5b3770293a Merge pull request 'docs: link entities to platform-docs READMEs' (#6) from documentor-annotations-1a23c5f4 into main
All checks were successful
Build and Publish TechDocs / build-and-publish (push) Successful in 53s
Reviewed-on: #6
2026-05-21 08:08:53 +00:00
1a80f57330 docs: set docs.kyndemo.live/readme for component/default/sonar-test-nest4 [documentor-agent]
All checks were successful
Integration Test / Platform Conformance (pull_request) Successful in 4s
SonarQube Analysis / Build, Test & Analyse (pull_request) Successful in 1m31s
Integration Test / Unit Tests + Container Smoke (workflow_dispatch) All checks passed
Integration Test / Unit Tests + Container Smoke (pull_request) Successful in 4m44s
2026-05-21 07:56:01 +00:00
fbae47fb29 Update README.md 2026-05-21 07:51:01 +00:00
3b93de198d Update catalog-info.yaml
All checks were successful
Build and Publish TechDocs / build-and-publish (push) Successful in 55s
2026-05-21 07:45:49 +00:00
e5ef7bbc27 Merge pull request 'docs: link entities to platform-docs READMEs' (#5) from documentor-annotations-9e0e917a into main
All checks were successful
Build and Publish TechDocs / build-and-publish (push) Successful in 1m2s
Reviewed-on: #5
2026-05-21 07:26:15 +00:00
194e432143 docs: set docs.kyndemo.live/readme for component/default/sonar-test-nest4 [documentor-agent]
All checks were successful
Integration Test / Unit Tests + Container Smoke (workflow_dispatch) All checks passed
Integration Test / Platform Conformance (pull_request) Successful in 4s
Integration Test / Unit Tests + Container Smoke (pull_request) Successful in 1m18s
SonarQube Analysis / Build, Test & Analyse (pull_request) Successful in 1m31s
2026-05-18 10:04:06 +00:00
0fd74664ea Update catalog-info.yaml
All checks were successful
Build and Publish TechDocs / build-and-publish (push) Successful in 54s
2026-05-18 10:01:58 +00:00
bd67d424f0 Update docs/architecture.md
All checks were successful
Build and Publish TechDocs / build-and-publish (push) Successful in 55s
2026-05-18 09:43:34 +00:00
e661b86f3a Update README.md 2026-05-18 09:18:41 +00:00
af14760e8f Merge pull request 'docs: link component/default/sonar-test-nest4 to platform-docs README' (#4) from documentor-agent-component-default-sonar-test-nest4-doc-c2a4ce0c8ba8-annotation into main
Reviewed-on: #4
2026-05-14 12:43:41 +00:00
1097d54a43 Merge pull request 'docs: link component/default/sonar-test-nest4 to platform-docs README' (#3) from documentor-agent-component-default-sonar-test-nest4-doc-c36e042daba8-annotation into main
Reviewed-on: #3
2026-05-14 12:42:15 +00:00
ff491bcef7 Merge pull request 'docs: link component/default/sonar-test-nest4 to platform-docs README' (#2) from documentor-agent-component-default-sonar-test-nest4-doc-11b79abf7f12-annotation into main
All checks were successful
Build and Publish TechDocs / build-and-publish (push) Successful in 1m0s
Reviewed-on: #2
2026-05-14 12:39:51 +00:00
9f9e41792c docs: set docs.kyndemo.live/readme for component/default/sonar-test-nest4 [documentor-agent]
Some checks failed
Integration Test / Unit Tests + Container Smoke (workflow_dispatch) All checks passed
Integration Test / Platform Conformance (pull_request) Successful in 5s
SonarQube Analysis / Build, Test & Analyse (pull_request) Failing after 1m25s
Integration Test / Unit Tests + Container Smoke (pull_request) Successful in 1m25s
2026-05-14 12:04:46 +00:00
05308edc60 docs: set docs.kyndemo.live/readme for component/default/sonar-test-nest4 [documentor-agent]
Some checks failed
Integration Test / Unit Tests + Container Smoke (workflow_dispatch) All checks passed
Integration Test / Platform Conformance (pull_request) Successful in 4s
Integration Test / Unit Tests + Container Smoke (pull_request) Successful in 1m22s
SonarQube Analysis / Build, Test & Analyse (pull_request) Failing after 1m35s
2026-05-14 12:04:38 +00:00
caaecfe856 docs: set docs.kyndemo.live/readme for component/default/sonar-test-nest4 [documentor-agent]
Some checks failed
Integration Test / Unit Tests + Container Smoke (workflow_dispatch) All checks passed
Integration Test / Platform Conformance (pull_request) Successful in 4s
SonarQube Analysis / Build, Test & Analyse (pull_request) Failing after 1m23s
Integration Test / Unit Tests + Container Smoke (pull_request) Successful in 1m19s
2026-05-14 12:03:43 +00:00
8d8fb6e13c Merge pull request 'sonarQ test on PR' (#1) from dev into main
Reviewed-on: #1
2026-05-12 10:38:21 +00:00
e143d46ad6 Update .gitea/workflows/sonar.yml
All checks were successful
Integration Test / Unit Tests + Container Smoke (pull_request) Successful in 5m19s
Build and Push to ACR / Build and Push (push) Successful in 1m21s
Integration Test / Platform Conformance (pull_request) Successful in 3s
SonarQube Analysis / Build, Test & Analyse (pull_request) Successful in 2m27s
Integration Test / Unit Tests + Container Smoke (workflow_dispatch) All checks passed
2026-05-11 15:04:09 +00:00
a9196c3dd7 Update README.md
Some checks failed
Integration Test / Unit Tests + Container Smoke (pull_request) Successful in 5m22s
Build and Push to ACR / Build and Push (push) Successful in 1m5s
Integration Test / Platform Conformance (pull_request) Successful in 4s
SonarQube Analysis / Build, Test & Analyse (pull_request) Failing after 12s
Integration Test / Unit Tests + Container Smoke (workflow_dispatch) All checks passed
2026-05-11 14:55:52 +00:00
2817e257aa feat(k6): add bespoke load test files
All checks were successful
Build and Push to ACR / Build and Push (push) Successful in 4m58s
2026-05-11 14:48:32 +00:00
4cecff9702 feat(scaffold): add src/items/items.service.ts [skip ci] 2026-05-11 14:48:09 +00:00
969d3212c6 feat(scaffold): add src/items/items.service.spec.ts [skip ci] 2026-05-11 14:48:08 +00:00
52dd7c69aa feat(scaffold): add src/items/items.module.ts [skip ci] 2026-05-11 14:48:08 +00:00
16ea66cb24 feat(scaffold): add src/items/items.controller.ts [skip ci] 2026-05-11 14:48:07 +00:00
ef4db6f659 feat(scaffold): add src/tracing.ts [skip ci] 2026-05-11 14:48:06 +00:00
7ff75ea179 feat(scaffold): add src/main.ts [skip ci] 2026-05-11 14:48:06 +00:00
10deefe8df feat(scaffold): add src/health.controller.ts [skip ci] 2026-05-11 14:48:05 +00:00
a49c88f06a feat(scaffold): add src/app.module.ts [skip ci] 2026-05-11 14:48:04 +00:00
69b94fec95 feat(scaffold): add tsconfig.json [skip ci] 2026-05-11 14:48:03 +00:00
f75a47d3e7 feat(scaffold): add package.json [skip ci] 2026-05-11 14:48:03 +00:00
45f083e6ae feat(scaffold): add Dockerfile [skip ci] 2026-05-11 14:48:02 +00:00
2fce030a82 feat(scaffold): add .gitignore [skip ci] 2026-05-11 14:48:01 +00:00
19 changed files with 500 additions and 111 deletions

View File

@@ -1,4 +1,3 @@
name: SonarQube Analysis
on:
@@ -124,7 +123,7 @@ jobs:
echo "SCAN_TOKEN=${SCAN_TOKEN}" >> "$GITHUB_ENV"
- name: Install dependencies and test
run: |
npm ci
npm install
npm run test:cov
- name: SonarQube analysis

5
.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules/
dist/
npm-debug.log*
.env
.DS_Store

30
Dockerfile Normal file
View File

@@ -0,0 +1,30 @@
# ---- Build stage ----
FROM node:20-alpine AS build
WORKDIR /app
COPY package.json ./
RUN npm install
COPY tsconfig.json ./
COPY src/ ./src/
RUN npm run build && npm prune --omit=dev
# ---- Runtime stage ----
FROM node:20-alpine
WORKDIR /app
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
COPY package.json ./
RUN chown -R appuser:appgroup /app
USER appuser
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD wget -qO- http://localhost:3000/health | grep -q 'UP' || exit 1
CMD ["node", "--require", "./dist/tracing.js", "dist/main"]

View File

@@ -1,4 +1,4 @@
# sonar-test-nest4
# sonar-test-nest4 test for doc agent catching sha change 21.5.2026 test 001
> **System-of-Record branch** — application code lives on `dev`.
@@ -21,3 +21,5 @@ is migrated to a different runtime.
| `runtime` | `typescript-nestjs` |
| `health_path` | `/health` |
| `container_port` | `3000` |

View File

@@ -6,62 +6,56 @@ metadata:
annotations:
humanitec.com/orgId: skillful-wild-chicken-2617
humanitec.com/projectId: domain-demo-apps
cjot.io/target-domain: "demo-apps"
cjot.io/target-domain: demo-apps
backstage.io/techdocs-ref: dir:.
backstage.io/kubernetes-namespace: dev
backstage.io/kubernetes-namespaces: "dev"
backstage.io/kubernetes-label-selector: "app=sonar-test-nest4"
gitea.kyndemo.live/repo-slug: "validate/sonar-test-nest4"
backstage.io/kubernetes-namespaces: dev
backstage.io/kubernetes-label-selector: app=sonar-test-nest4
gitea.kyndemo.live/repo-slug: validate/sonar-test-nest4
sonarqube.org/project-key: sonar-test-nest4
prometheus.io/scrape: "true"
prometheus.io/port: "3000"
prometheus.io/path: "/metrics"
prometheus.io/scrape: 'true'
prometheus.io/port: '3000'
prometheus.io/path: /metrics
grafana/grafana-instance: default
grafana/alert-label-selector: "app=sonar-test-nest4"
grafana/dashboard-selector: "uid == 'otel-app-observability-v2'"
grafana.com/alert-label-selector: "app=sonar-test-nest4"
grafana.com/dashboard-url: "https://grafana.kyndemo.live/d/otel-app-observability-v2/opentelemetry-application-observability?orgId=1&var-app=sonar-test-nest4"
chaos-mesh/enabled: "true"
k6/enabled: "true"
k6/test-configmap: "k6-test-sonar-test-nest4"
k6/test-namespace: "dev"
k6/target-service: "sonar-test-nest4"
k6/target-port: "3000"
grafana/alert-label-selector: app=sonar-test-nest4
grafana/dashboard-selector: uid == 'otel-app-observability-v2'
grafana.com/alert-label-selector: app=sonar-test-nest4
grafana.com/dashboard-url:
https://grafana.kyndemo.live/d/otel-app-observability-v2/opentelemetry-application-observability?orgId=1&var-app=sonar-test-nest4
chaos-mesh/enabled: 'true'
k6/enabled: 'true'
k6/test-configmap: k6-test-sonar-test-nest4
k6/test-namespace: dev
k6/target-service: sonar-test-nest4
k6/target-port: '3000'
docs.kyndemo.live/readme:
catalog/component/default/sonar-test-nest4/README.md
tags:
- microservice
- golden-path
- typescript-nestjs
- stateless
- opentelemetry
- load-testing
- k6
- microservice
- golden-path
- typescript-nestjs
- stateless
- opentelemetry
- load-testing
- k6
links:
- url: https://console.humanitec.dev/orgs/skillful-wild-chicken-2617/projects/domain-demo-apps
title: Humanitec Console
icon: dashboard
- url: https://grafana.kyndemo.live/d/otel-app-observability-v2/opentelemetry-application-observability?orgId=1&var-app=sonar-test-nest4
title: Grafana Dashboard
icon: dashboard
- url: https://gitea.kyndemo.live/validate/sonar-test-nest4
title: Source Repository
icon: github
- url:
https://console.humanitec.dev/orgs/skillful-wild-chicken-2617/projects/domain-demo-apps
title: Humanitec Console
icon: dashboard
- url:
https://grafana.kyndemo.live/d/otel-app-observability-v2/opentelemetry-application-observability?orgId=1&var-app=sonar-test-nest4
title: Grafana Dashboard
icon: dashboard
- url: https://gitea.kyndemo.live/validate/sonar-test-nest4
title: Source Repository
icon: github
spec:
type: service
owner: group:default/platform-engineering
lifecycle: experimental
providesApis:
- sonar-test-nest4-api
- sonar-test-nest4-api
---
apiVersion: backstage.io/v1alpha1
kind: API
@@ -74,66 +68,20 @@ spec:
type: openapi
lifecycle: experimental
owner: group:default/platform-engineering
definition: |
openapi: "3.0.0"
info:
title: sonar-test-nest4
version: "0.1.0"
description: "sonar-test-nest4"
servers:
- url: https://sonar-test-nest4.kyndemo.live
paths:
/api/items:
get:
summary: List all items
responses:
"200":
description: OK
post:
summary: Create item
responses:
"201":
description: Created
/api/items/{id}:
get:
summary: Get by ID
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
"200":
description: OK
"404":
description: Not found
put:
summary: Update item
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
"200":
description: OK
delete:
summary: Update item
parameters:
- name: id
in: path
required: true
schema:
type: integer
responses:
"200":
description: Deleted
/health:
get:
summary: Health check
responses:
"200":
description: "{ status: UP }"
definition: "openapi: \"3.0.0\"\ninfo:\n title: sonar-test-nest4\n version: \"\
0.1.0\"\n description: \"sonar-test-nest4\"\nservers:\n - url: https://sonar-test-nest4.kyndemo.live\n\
paths:\n /api/items:\n get:\n summary: List all items\n responses:\n\
\ \"200\":\n description: OK\n post:\n summary: Create
item\n responses:\n \"201\":\n description: Created\n /api/items/{id}:\n\
\ get:\n summary: Get by ID\n parameters:\n - name: id\n \
\ in: path\n required: true\n schema:\n type:
integer\n responses:\n \"200\":\n description: OK\n \
\ \"404\":\n description: Not found\n put:\n summary: Update
item\n parameters:\n - name: id\n in: path\n required:
true\n schema:\n type: integer\n responses:\n \
\ \"200\":\n description: OK\n delete:\n summary: Update item\n\
\ parameters:\n - name: id\n in: path\n required:
true\n schema:\n type: integer\n responses:\n \
\ \"200\":\n description: Deleted\n /health:\n get:\n summary:
Health check\n responses:\n \"200\":\n description: \"{ status:
UP }\"\n"

View File

@@ -18,6 +18,9 @@ Push to dev/staging/prod
→ deploy-humanitec.yml (hctl score deploy)
```
## Deployment alternative method
## Branch model
| Branch | Purpose |

53
k6/configmap.yaml Normal file
View File

@@ -0,0 +1,53 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: k6-test-sonar-test-nest4
namespace: dev
labels:
app: sonar-test-nest4
app.kubernetes.io/managed-by: backstage
app.kubernetes.io/component: load-testing
data:
K6_OUT: opentelemetry
K6_OTEL_GRPC_EXPORTER_INSECURE: 'true'
K6_OTEL_GRPC_EXPORTER_ENDPOINT: otel-collector.monitoring.svc.cluster.local:4317
K6_OTEL_METRIC_PREFIX: k6_
K6_OTEL_FLUSH_INTERVAL: '1000'
K6_OTEL_EXPORT_INTERVAL: '5000'
K6_OTEL_SERVICE_NAME: k6-sonar-test-nest4
load-test.js: "import http from 'k6/http';\nimport { check, sleep, group } from\
\ 'k6';\n\nconst vus = parseInt(__ENV.TEST_VUS || '10');\nconst duration = __ENV.TEST_DURATION\
\ || '30s';\nconst targetUrl = __ENV.TARGET_URL || 'http://sonar-test-nest4.dev.svc.cluster.local:3000';\n\
\nexport const options = {\n scenarios: {\n load_test: {\n executor:\
\ 'ramping-vus',\n startVUs: 0,\n stages: [\n { duration: '10s',\
\ target: vus },\n { duration: duration, target: vus },\n { duration:\
\ '5s', target: 0 },\n ],\n },\n },\n thresholds: {\n http_req_duration:\
\ ['p(95)<500'],\n http_req_failed: ['rate<0.01'],\n },\n};\n\nhttp.setResponseCallback(http.expectedStatuses({\
\ min: 200, max: 399 }));\n\nexport default function () {\n group('Health API',\
\ () => {\n const res = http.get(`${targetUrl}/health`);\n check(res, {\n\
\ 'status is 200': (r) => r.status === 200,\n 'response time < 500ms':\
\ (r) => r.timings.duration < 500,\n });\n });\n\n sleep(0.5);\n\n group('Items\
\ API', () => {\n const resGetAll = http.get(`${targetUrl}/api/items`);\n \
\ check(resGetAll, {\n 'status is 200': (r) => r.status === 200,\n \
\ 'response time < 500ms': (r) => r.timings.duration < 500,\n 'body contains\
\ items': (r) => Array.isArray(JSON.parse(r.body)),\n });\n\n const resCreate\
\ = http.post(\n `${targetUrl}/api/items`,\n JSON.stringify({ name:\
\ 'Test Item', description: 'A test description' }),\n { headers: { 'Content-Type':\
\ 'application/json' } }\n );\n check(resCreate, {\n 'status is 201':\
\ (r) => r.status === 201,\n 'response time < 500ms': (r) => r.timings.duration\
\ < 500,\n 'body contains id': (r) => JSON.parse(r.body).id !== undefined,\n\
\ });\n\n const itemId = JSON.parse(resCreate.body).id;\n\n const resGetOne\
\ = http.get(`${targetUrl}/api/items/${itemId}`);\n check(resGetOne, {\n \
\ 'status is 200': (r) => r.status === 200,\n 'response time < 500ms':\
\ (r) => r.timings.duration < 500,\n 'body contains correct item': (r) =>\
\ JSON.parse(r.body).id === itemId,\n });\n\n const resUpdate = http.put(\n\
\ `${targetUrl}/api/items/${itemId}`,\n JSON.stringify({ name: 'Updated\
\ Item', description: 'Updated description' }),\n { headers: { 'Content-Type':\
\ 'application/json' } }\n );\n check(resUpdate, {\n 'status is 200':\
\ (r) => r.status === 200,\n 'response time < 500ms': (r) => r.timings.duration\
\ < 500,\n 'body contains updated item': (r) => JSON.parse(r.body).name ===\
\ 'Updated Item',\n });\n\n const resDelete = http.del(`${targetUrl}/api/items/${itemId}`);\n\
\ check(resDelete, {\n 'status is 200': (r) => r.status === 200,\n \
\ 'response time < 500ms': (r) => r.timings.duration < 500,\n 'body confirms\
\ deletion': (r) => JSON.parse(r.body).deleted === itemId,\n });\n });\n\n\
\ sleep(0.5);\n}"

87
k6/load-test.js Normal file
View File

@@ -0,0 +1,87 @@
import http from 'k6/http';
import { check, sleep, group } from 'k6';
const vus = parseInt(__ENV.TEST_VUS || '10');
const duration = __ENV.TEST_DURATION || '30s';
const targetUrl = __ENV.TARGET_URL || 'http://sonar-test-nest4.dev.svc.cluster.local:3000';
export const options = {
scenarios: {
load_test: {
executor: 'ramping-vus',
startVUs: 0,
stages: [
{ duration: '10s', target: vus },
{ duration: duration, target: vus },
{ duration: '5s', target: 0 },
],
},
},
thresholds: {
http_req_duration: ['p(95)<500'],
http_req_failed: ['rate<0.01'],
},
};
http.setResponseCallback(http.expectedStatuses({ min: 200, max: 399 }));
export default function () {
group('Health API', () => {
const res = http.get(`${targetUrl}/health`);
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
});
sleep(0.5);
group('Items API', () => {
const resGetAll = http.get(`${targetUrl}/api/items`);
check(resGetAll, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
'body contains items': (r) => Array.isArray(JSON.parse(r.body)),
});
const resCreate = http.post(
`${targetUrl}/api/items`,
JSON.stringify({ name: 'Test Item', description: 'A test description' }),
{ headers: { 'Content-Type': 'application/json' } }
);
check(resCreate, {
'status is 201': (r) => r.status === 201,
'response time < 500ms': (r) => r.timings.duration < 500,
'body contains id': (r) => JSON.parse(r.body).id !== undefined,
});
const itemId = JSON.parse(resCreate.body).id;
const resGetOne = http.get(`${targetUrl}/api/items/${itemId}`);
check(resGetOne, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
'body contains correct item': (r) => JSON.parse(r.body).id === itemId,
});
const resUpdate = http.put(
`${targetUrl}/api/items/${itemId}`,
JSON.stringify({ name: 'Updated Item', description: 'Updated description' }),
{ headers: { 'Content-Type': 'application/json' } }
);
check(resUpdate, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
'body contains updated item': (r) => JSON.parse(r.body).name === 'Updated Item',
});
const resDelete = http.del(`${targetUrl}/api/items/${itemId}`);
check(resDelete, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
'body confirms deletion': (r) => JSON.parse(r.body).deleted === itemId,
});
});
sleep(0.5);
}

24
k6/testrun.yaml Normal file
View File

@@ -0,0 +1,24 @@
apiVersion: k6.io/v1alpha1
kind: TestRun
metadata:
name: k6-sonar-test-nest4
namespace: dev
labels:
app: sonar-test-nest4
backstage.io/component: sonar-test-nest4
app.kubernetes.io/managed-by: backstage
app.kubernetes.io/component: load-testing
spec:
parallelism: 1
script:
configMap:
name: k6-test-sonar-test-nest4
file: load-test.js
runner:
image: grafana/k6:latest
envFrom:
- configMapRef:
name: k6-test-sonar-test-nest4
env:
- name: K6_OTEL_SERVICE_NAME
value: k6-sonar-test-nest4

44
package.json Normal file
View File

@@ -0,0 +1,44 @@
{
"name": "sonar-test-nest4",
"version": "0.1.0",
"description": "sonar-test-nest4",
"scripts": {
"build": "nest build",
"start": "node dist/main",
"start:dev": "nest start --watch",
"test": "jest",
"test:cov": "jest --coverage"
},
"dependencies": {
"@nestjs/common": "^10.3.8",
"@nestjs/core": "^10.3.8",
"@nestjs/platform-express": "^10.3.8",
"@nestjs/terminus": "^10.2.3",
"@willsoto/nestjs-prometheus": "^6.0.1",
"prom-client": "^15.1.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"@opentelemetry/sdk-node": "^0.52.0",
"@opentelemetry/auto-instrumentations-node": "^0.47.0",
"@opentelemetry/exporter-trace-otlp-http": "^0.52.0",
"@opentelemetry/exporter-metrics-otlp-http": "^0.52.0"
},
"devDependencies": {
"@nestjs/cli": "^10.3.2",
"@nestjs/testing": "^10.3.8",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.11",
"jest": "^29.7.0",
"ts-jest": "^29.1.3",
"typescript": "^5.4.5"
},
"jest": {
"moduleFileExtensions": ["js","json","ts"],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": { "^.+\\.(t|j)s$": "ts-jest" },
"testEnvironment": "node",
"coverageDirectory": "coverage",
"coverageReporters": ["lcov", "text-summary"]
}
}

15
src/app.module.ts Normal file
View File

@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
import { ItemsModule } from './items/items.module';
import { HealthController } from './health.controller';
@Module({
imports: [
TerminusModule,
PrometheusModule.register({ path: '/metrics' }),
ItemsModule,
],
controllers: [HealthController],
})
export class AppModule {}

13
src/health.controller.ts Normal file
View File

@@ -0,0 +1,13 @@
import { Controller, Get } from '@nestjs/common';
import { HealthCheck, HealthCheckService } from '@nestjs/terminus';
@Controller('health')
export class HealthController {
constructor(private health: HealthCheckService) {}
@Get()
@HealthCheck()
check() {
return this.health.check([]);
}
}

View File

@@ -0,0 +1,48 @@
import {
Body,
Controller,
Delete,
Get,
HttpCode,
Param,
ParseIntPipe,
Post,
Put,
} from '@nestjs/common';
import { ItemsService } from './items.service';
class CreateItemDto {
name: string;
description?: string;
}
@Controller('api/items')
export class ItemsController {
constructor(private readonly items: ItemsService) {}
@Get()
findAll() {
return this.items.findAll();
}
@Post()
@HttpCode(201)
create(@Body() dto: CreateItemDto) {
return this.items.create(dto.name, dto.description);
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.items.findOne(id);
}
@Put(':id')
update(@Param('id', ParseIntPipe) id: number, @Body() dto: CreateItemDto) {
return this.items.update(id, dto.name, dto.description);
}
@Delete(':id')
remove(@Param('id', ParseIntPipe) id: number) {
return this.items.remove(id);
}
}

View File

@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { ItemsController } from './items.controller';
import { ItemsService } from './items.service';
@Module({
controllers: [ItemsController],
providers: [ItemsService],
})
export class ItemsModule {}

View File

@@ -0,0 +1,19 @@
import { Test, TestingModule } from '@nestjs/testing';
import { ItemsService } from './items.service';
describe('ItemsService', () => {
let service: ItemsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ItemsService],
}).compile();
service = module.get<ItemsService>(ItemsService);
});
it('creates and retrieves an item', () => {
const item = service.create('Widget', 'A test widget');
expect(item.id).toBe(1);
expect(service.findOne(1).name).toBe('Widget');
});
});

View File

@@ -0,0 +1,45 @@
import { Injectable, NotFoundException } from '@nestjs/common';
export interface Item {
id: number;
name: string;
description: string;
}
@Injectable()
export class ItemsService {
private readonly store = new Map<number, Item>();
private counter = 1;
findAll(): Item[] {
return [...this.store.values()];
}
create(name: string, description = ''): Item {
const item: Item = { id: this.counter++, name, description };
this.store.set(item.id, item);
return item;
}
findOne(id: number): Item {
const item = this.store.get(id);
if (!item) throw new NotFoundException(`Item ${id} not found`);
return item;
}
update(id: number, name?: string, description?: string): Item {
const item = this.findOne(id);
const updated: Item = {
id,
name: name ?? item.name,
description: description ?? item.description,
};
this.store.set(id, updated);
return updated;
}
remove(id: number): { deleted: number } {
this.store.delete(id);
return { deleted: id };
}
}

9
src/main.ts Normal file
View File

@@ -0,0 +1,9 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(process.env.PORT ?? 3000);
console.log(`sonar-test-nest4 listening on :${process.env.PORT ?? 3000}`);
}
bootstrap();

19
src/tracing.ts Normal file
View File

@@ -0,0 +1,19 @@
// OTel SDK bootstrap — loaded via --require ./dist/tracing.js before the app.
// Auto-configures from OTEL_* env vars set in score.yaml / Humanitec.
// No-ops gracefully when OTEL_EXPORTER_OTLP_ENDPOINT is absent (local dev).
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
if (endpoint) {
const sdk = new NodeSDK({
instrumentations: [
getNodeAutoInstrumentations({
'@opentelemetry/instrumentation-fs': { enabled: false },
}),
],
});
sdk.start();
process.on('SIGTERM', () => sdk.shutdown().finally(() => process.exit(0)));
}

17
tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": false
}
}