Gathering detailed insights and metrics for @biblioteksentralen/cloud-run-core
Gathering detailed insights and metrics for @biblioteksentralen/cloud-run-core
Gathering detailed insights and metrics for @biblioteksentralen/cloud-run-core
Gathering detailed insights and metrics for @biblioteksentralen/cloud-run-core
npm install @biblioteksentralen/cloud-run-core
Typescript
Module System
Min. Node Version
Node Version
NPM Version
Cumulative downloads
Total Downloads
8
This package contains some core functionality for Node.js services running on Google Cloud Run, such as logging and error handling.
1▶ pnpm install 2▶ pnpm test
Publishing the package:
1▶ pn changeset # create a new changeset 2▶ pn changeset version # updates version number and changelog 3▶ git commit -m "publish vX.X.X" 4▶ pn changeset publish 5▶ git push --follow-tags
1▶ npm install @biblioteksentralen/cloud-run-core
To create an Express-based HTTP service:
1// src/start.ts 2import { createService } from "@biblioteksentralen/cloud-run-core"; 3import { z } from "zod"; 4 5const projectId = z.string().parse(process.env.GCP_PROJECT_ID); 6const service = createService("fun-service", { projectId }); 7 8service.router.get("/", async (req, res) => { 9 req.log.info(`Hello log!`); 10 // ... 11}); 12 13service.start();
The HTTP service comes pre-configured with a logging middleware that sets up Pino to structure logs for Google Cloud Logging with trace context. The logger is added to the Express Request context, so it can be used in all request handlers:
1// src/endpoints/funRequestHandler.ts 2import { Request, Response } from "@biblioteksentralen/cloud-run-core"; 3 4export async function funRequestHandler(req: Request, res: Response): Promise<void> { 5 req.log.info(`Hello log!`); 6}
1// src/start.ts 2// ... 3import { funRequestHandler } from "./endpoints/funRequestHandler.js"; 4 5// ... 6service.router.get("/", funRequestHandler);
In scripts / GCP Cloud Run Jobs:
1import { logger } from "@biblioteksentralen/cloud-run-core" 2 3logger.info({ someProperty: "someValue" }, "Hello world")
The logger is configured so it formats logs as JSON structured for GCP Cloud Logging when running in GCP, or when output is piped to another process (no TTY), and with pino-pretty otherwise.
To manually disable pino-pretty, set the environment variable PINO_PRETTY=false
.
LOG_LEVEL
- Control minimum log levelThe environment variable LOG_LEVEL
can be used to control the minimum log level.
Defaults to debug
.
Use createRouter()
to create modular, mountable route handlers (uses express.Router()
):
1// src/start.ts 2import { createService, createRouter } from "@biblioteksentralen/cloud-run-core"; 3import { z } from "zod"; 4 5const projectId = z.string().parse(process.env.GCP_PROJECT_ID); 6const service = createService("fun-service", { projectId }); 7 8const adminRouter = createRouter() 9 10adminRouter.get("/", async (req, res) => { 11 req.log.info(`Hello admin`); 12 // ... 13}); 14 15service.router.use("/admin", adminRouter); 16 17service.start();
This package provides an error handling middleware that is automatically
attached to the service when you start the service using service.start()
,
inspired by How to Handle Errors in Express with
TypeScript.
AppError
is a base class to be used for all known application errors (that is,
all errors we throw ourselves).
1// src/endpoints/funRequestHandler.ts
2import { AppError, Request, Response } from "@biblioteksentralen/cloud-run-core";
3
4export async function funRequestHandler(req: Request, res: Response) {
5 // ...
6 throw new AppError('🔥 Databasen har brent ned');
7 // ...
8}
As long as errors are thrown before writing the response has started, a JSON error response is produced on the form:
1{ "error": "🔥 Databasen har brent ned" }
By default, errors based on AppError
are considered operational and displayed
in responses. If an error should not be displayed, set isOperational: false
when constructing the error:
1throw new AppError('🔥 Databasen har brent ned', { isOperational: false });
This results in a generic error response (but the original error is still logged):
1{ "error": "Internal server error" }
A generic error response will also be shown for any unknown error, that is,
any error that is not based on AppError
) is thrown. All errors, both known and
unknown, are logged.
By default, errors use status code 500. To use another status code:
1throw new AppError('💤 Too early', { httpStatus: 425 });
The package also provides a few subclasses of AppError
for common use cases,
such as ClientRequestError
(yields 400 response) and Unauthorized
(yields
401 response).
1throw new Unauthorized('🔒 Unauthorized');
Set sentry.dsn
when creating the client to enable Sentry error reporting and telemetry.
1import { createService } from "@biblioteksentralen/cloud-run-core";
2
3const service = createService("fun-service", {
4 sentry: {
5 dsn: process.env.SENTRY_DSN,
6 tracesSampleRate: 0.1,
7 environment: process.env.NODE_ENV, // or similar
8 ...
9 },
10 ...
11});
The package uses http-terminator to
gracefully terminate the HTTP server when the process exists (on SIGTERM). An
event, shutdown
, is emitted after the server has shut down. You can listen to
this if you want to do additional cleanup, such as closing database connections.
1// src/start.ts 2import { createService } from "@biblioteksentralen/cloud-run-core"; 3import { z } from "zod"; 4 5const projectId = z.string().parse(process.env.GCP_PROJECT_ID); 6const service = createService("fun-service", { projectId }); 7 8service.on("shutdown", async () => { 9 await db.close() 10}); 11 12// ... 13 14service.start();
The package provides a helper function to parse and validate Pub/Sub messages delivered through push delivery.
The package is agnostic when it comes to which schema parsing/validation library to use, but we recommend using Zod.
1import { z } from "zod"; 2import { 3 parsePubSubMessage, 4 Request, 5 Response, 6} from "@biblioteksentralen/cloud-run-core"; 7 8const messageSchema = z.object({ 9 table: z.string(), 10 key: z.number(), 11}); 12 13app.post("/", async (req: Request, res: Response) => { 14 const message = parsePubSubMessage(req); 15 const data = messageSchema.parse(JSON.parse(message.data)); 16 // ... 17});
1import { isCloudRunEnvironment } from "@biblioteksentralen/cloud-run-core"; 2 3isCloudRunEnvironment()
will return true if running as a Cloud Run Service or Job.
We include @types/express
as a dependency, not a devDependency, because we
extend and re-export the Request interface. Initially we kept it under
devDependencies, but then all package consumers would have to install the
package themselves. Not sure what's considered best practice in cases like
this though.
@sentry
-pakkene kan av og til komme ut av sync med hverandre. De jobber med
å redusere mengden pakker for å redusere problemet:
https://github.com/getsentry/sentry-javascript/issues/8965#issuecomment-1709923865
Inntil videre kan en prøve å oppdatere alle pakker og se om en klarer å få
like versjoner fra pn ls --depth 3 @sentry/types
No vulnerabilities found.
No security vulnerabilities found.
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year