### Jest Setup and Teardown Implementation
Source: https://github.com/tsedio/tsed/blob/production/packages/testcontainers/postgres/readme.md
Example implementation for Jest setup and teardown files to start and stop the PostgreSQL container.
```typescript
// jest.config.js
module.exports = {
globalSetup: ["jest.setup.js"],
globalTeardown: ["jest.teardown.js"]
};
// jest.setup.js
import {TestContainersPostgres} from "@tsedio/testcontainers-postgres";
export default async () => {
await TestContainersPostgres.startContainer();
};
// jest.teardown.js
import {TestContainersPostgres} from "@tsedio/testcontainers-postgres";
export default async () => {
await TestContainersPostgres.stopContainer();
};
```
--------------------------------
### Basic PostgreSQL Testcontainers Setup
Source: https://github.com/tsedio/tsed/blob/production/docs/plugins/premium/testcontainers/postgres.md
Demonstrates the basic setup for using Testcontainers with PostgreSQL. It shows how to get the connection URL and reset the database after tests.
```typescript
import {TestContainersPostgres} from "@tsedio/testcontainers-postgres";
describe("MyTest", () => {
beforeEach(() => {
const connectionString = TestContainersPostgres.getUrl();
console.log(connectionString);
});
afterEach(async () => {
await TestContainersPostgres.reset();
});
});
```
--------------------------------
### Start Local Emulation with Serverless Offline
Source: https://github.com/tsedio/tsed/blob/production/packages/platform/platform-serverless-http/test/integration/aws-basic/README.md
Once the `serverless-offline` plugin is installed, run this command to start local emulation of API Gateway and Lambda.
```bash
serverless offline
```
--------------------------------
### Jest Setup File for TestContainers PostgreSQL
Source: https://github.com/tsedio/tsed/blob/production/docs/plugins/premium/testcontainers/postgres.md
Implement the Jest global setup file to start the PostgreSQL TestContainer.
```typescript
// jest.config.js
module.exports = {
globalSetup: ["jest.setup.js"],
globalTeardown: ["jest.teardown.js"]
};
// jest.setup.js
import {TestContainersPostgres} from "@tsedio/testcontainers-postgres";
export default async () => {
await TestContainersPostgres.startContainer();
};
```
--------------------------------
### Fastify Adapter Test Example
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/platform-adapter.md
Example test setup for the Fastify platform adapter. It uses PlatformTestSdk to initialize tests for handlers.
```typescript
// platform-fastify.spec.ts
import {PlatformTestSdk} from "@tsed/platform-test-sdk";
import {PlatformFastify} from "../src/components/PlatformFastify";
import {rootDir, Server} from "./app/Server";
const utils = PlatformTestSdk.create({
rootDir,
adapter: PlatformFastify,
server: Server,
logger: {
level: "off"
}
});
describe("PlatformFastify", () => {
describe("Handlers", () => {
utils.test("handlers");
});
// More tests...
});
```
--------------------------------
### Jest Setup File for Vault Container
Source: https://github.com/tsedio/tsed/blob/production/packages/testcontainers/vault/readme.md
Create a Jest setup file to start the Vault container before tests run.
```typescript
// jest.setup.js
import {TestContainersVault} from "@tsedio/testcontainers-vault";
module.exports = async () => {
await TestContainersVault.startContainer();
};
```
--------------------------------
### Basic Socket.IO Client Connection (HTML)
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/socket-io.md
Plain JavaScript example for connecting to a Socket.IO server from a client. This snippet shows the basic setup using the Socket.IO client library.
```html
```
--------------------------------
### Install dot
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the dot template engine.
```sh
npm install dot
```
--------------------------------
### Install htmling
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the htmling template engine.
```sh
npm install htmling
```
--------------------------------
### Install @tsed/adapters with bun
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/adapters.md
Install the @tsed/adapters package using bun.
```sh
bun add @tsed/adapters
```
--------------------------------
### Install bracket-template
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the bracket-template template engine.
```sh
npm install bracket-template
```
--------------------------------
### Install hamlet
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the hamlet template engine.
```sh
npm install hamlet
```
--------------------------------
### Install hogan.js
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the hogan.js template engine.
```sh
npm install hogan.js
```
--------------------------------
### Install jazz
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the jazz template engine.
```sh
npm install jazz
```
--------------------------------
### Install @tsedio/config-vault with bun
Source: https://github.com/tsedio/tsed/blob/production/packages/config/vault/readme.md
Install the package and its dependencies using bun.
```sh
bun add @tsedio/config-vault
bun add @tsed/config node-vault
```
--------------------------------
### Install handlebars
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the handlebars template engine.
```sh
npm install handlebars
```
--------------------------------
### Install haml-coffee
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the haml-coffee template engine.
```sh
npm install haml-coffee
```
--------------------------------
### Install hamljs
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install the hamljs template engine.
```sh
npm install hamljs
```
--------------------------------
### Build and Serve Documentation
Source: https://github.com/tsedio/tsed/blob/production/AGENTS.md
Commands to build API documentation, build user documentation, and serve user documentation locally.
```bash
yarn api:build # Build API docs
yarn docs:build # Build user docs
yarn docs:serve # Serve docs locally
```
--------------------------------
### Jest Setup File for Vault TestContainers
Source: https://github.com/tsedio/tsed/blob/production/docs/plugins/premium/testcontainers/vault.md
Implement the Jest setup file to start the Vault TestContainers.
```ts
import {TestContainersVault} from "@tsedio/testcontainers-vault";
module.exports = async () => {
await TestContainersVault.startContainer();
};
```
--------------------------------
### Jest Setup File for Redis TestContainers
Source: https://github.com/tsedio/tsed/blob/production/docs/plugins/premium/testcontainers/redis.md
Create a Jest setup file to start the Redis container before tests.
```typescript
import {TestContainersRedis} from "@tsedio/testcontainers-redis";
module.exports = async () => {
await TestContainersRedis.startContainer();
};
```
--------------------------------
### Install Socket.io with bun
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/socket-io.md
Install the Socket.io module and its types using bun.
```sh
bun add socket.io @types/socket.io @tsed/socketio
bun add --dev @tsed/socketio-testing
```
--------------------------------
### Install Dependencies and Build Packages
Source: https://github.com/tsedio/tsed/blob/production/AGENTS.md
Commands to install dependencies, configure workspaces, and build all packages.
```bash
yarn install # Install dependencies via Yarn workspaces
yarn configure # Generate workspace package references
yarn build # Build all packages
yarn api:build # Generate API documentation
```
--------------------------------
### Jest setup and teardown files
Source: https://github.com/tsedio/tsed/blob/production/docs/plugins/premium/testcontainers/mongo.md
Implement Jest setup and teardown using TestContainersMongo to start and stop the MongoDB container.
```typescript
// jest.config.js
module.exports = {
globalSetup: ["jest.setup.js"],
globalTeardown: ["jest.teardown.js"]
};
// jest.setup.js
import {TestContainersMongo} from "@tsedio/testcontainers-mongo";
export default async () => {
await TestContainersMongo.startContainer();
};
// jest.teardown.js
import {TestContainersMongo} from "@tsedio/testcontainers-mongo";
export default async () => {
await TestContainersMongo.stopContainer();
};
```
--------------------------------
### Install IORedis and ioredis-mock
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/ioredis.md
Install the necessary packages for IORedis and its mock for testing.
```sh
npm install --save @tsed/ioredis ioredis
npm install --save-dev ioredis-mock
```
```sh
yarn add @tsed/ioredis ioredis
yarn add -D ioredis-mock
```
```sh
pnpm add @tsed/ioredis ioredis
pnpm add -D ioredis-mock
```
```sh
bun add @tsed/ioredis ioredis
bun add -D ioredis-mock
```
--------------------------------
### Koa Adapter Test Example
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/platform-adapter.md
Example test setup for the Koa platform adapter. It uses PlatformTestSdk to initialize tests for handlers.
```typescript
// platform-koa.spec.ts
import {PlatformTestSdk} from "@tsed/platform-test-sdk";
import {PlatformKoa} from "../src/components/PlatformKoa";
import {rootDir, Server} from "./app/Server";
const utils = PlatformTestSdk.create({
rootDir,
adapter: PlatformKoa,
server: Server,
logger: {
level: "off"
}
});
describe("PlatformKoa", () => {
describe("Handlers", () => {
utils.test("handlers");
});
// More tests...
});
```
--------------------------------
### Example Test Server Configuration
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/platform-adapter.md
Define a basic server configuration for your adapter tests. This includes setting the root directory and mounting controllers.
```typescript
// app/Server.ts
import {Configuration} from "@tsed/di";
import {PlatformYourFramework} from "../../src/components/PlatformYourFramework";
import path from "path";
export const rootDir = path.join(__dirname, "..");
@Configuration({
rootDir,
mount: {
"/rest": [`${rootDir}/controllers/**/*.ts`]
},
logger: {
level: "off"
}
})
export class Server {}
```
--------------------------------
### Install Supertest with bun
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/testing.md
Install supertest and its types for bun projects.
```sh
bun add -D supertest @types/supertest
```
--------------------------------
### Install Directus SDK with bun
Source: https://github.com/tsedio/tsed/blob/production/packages/third-parties/directus-sdk/readme.md
Install the Directus SDK package using bun.
```sh
bun add @tsed/directus-sdk
```
--------------------------------
### Express Adapter Test Example
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/platform-adapter.md
Example test setup for the Express platform adapter. It uses PlatformTestSdk to initialize tests for handlers.
```typescript
// platform-express.spec.ts
import {PlatformTestSdk} from "@tsed/platform-test-sdk";
import {PlatformExpress} from "../src/components/PlatformExpress";
import {rootDir, Server} from "./app/Server";
const utils = PlatformTestSdk.create({
rootDir,
adapter: PlatformExpress,
server: Server,
logger: {
level: "off"
}
});
describe("PlatformExpress", () => {
describe("Handlers", () => {
utils.test("handlers");
});
// More tests...
});
```
--------------------------------
### Install Vitest and Dependencies
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/vitest.md
Install Vitest and necessary SWC and coverage tools using your preferred package manager.
```bash
$ npm i --save-dev vitest unplugin-swc @swc/core @vitest/coverage-v8
```
```bash
$ yarn add -D vitest unplugin-swc @swc/core @vitest/coverage-v8
```
```bash
$ pnpm add -D vitest unplugin-swc @swc/core @vitest/coverage-v8
```
```bash
$ bun add -D vitest unplugin-swc @swc/core @vitest/coverage-v8
```
--------------------------------
### Install @tsedio/config-postgres with bun
Source: https://github.com/tsedio/tsed/blob/production/packages/config/postgres/readme.md
Install the package and its peer dependencies using bun.
```sh
bun add @tsedio/config-postgres
bun add @tsed/config pg
```
--------------------------------
### Install Dependencies and Build
Source: https://github.com/tsedio/tsed/blob/production/CONTRIBUTING.md
Install npm dependencies using yarn and then build the project. Ensure you use yarn, not npm, for dependency management.
```bash
yarn
yarn tsc --build
```
--------------------------------
### Test Session with Jest
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/testing.md
Example of testing session functionality using Jest. Ensure session is installed.
```typescript
import {Platform} from "@tsed/common";
import {SessionModule} from "@tsed/session";
describe("session", () => {
beforeEach(async () => {
await Platform.create({
imports: [SessionModule]
});
});
afterEach(async () => {
await Platform.reset();
});
it("should be logged in", async () => {
await Platform.request({url: "/login", method: "POST"});
const {body} = await Platform.request({url: "/logged-in"});
expect(body.userId).to.eql("test");
});
});
```
--------------------------------
### Test Session with Vitest
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/testing.md
Example of testing session functionality using Vitest. Ensure session is installed.
```typescript
import {Platform} from "@tsed/common";
import {SessionModule} from "@tsed/session";
import {describe, it, beforeEach, afterEach} from "vitest";
describe("session", () => {
beforeEach(async () => {
await Platform.create({
imports: [SessionModule]
});
});
afterEach(async () => {
await Platform.reset();
});
it("should be logged in", async () => {
await Platform.request({url: "/login", method: "POST"});
const {body} = await Platform.request({url: "/logged-in"});
expect(body.userId).to.eql("test");
});
});
```
--------------------------------
### Install Prisma Client
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/prisma.md
Install the Prisma Client package using npm. This command also automatically invokes `prisma generate`.
```bash
$ npm install @prisma/client
```
--------------------------------
### Vitest Configuration for Testcontainers
Source: https://github.com/tsedio/tsed/blob/production/packages/testcontainers/mongo/readme.md
Configure Vitest to use a global setup file for starting the MongoDB server with Testcontainers.
```ts
import {defineConfig} from "vitest/config";
export default defineConfig({
test: {
globalSetup: [import.meta.resolve("@tsed/mongo/vitest/setup")]
}
});
```
--------------------------------
### Install Socket.io with npm
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/socket-io.md
Install the Socket.io module and its types using npm.
```sh
npm install --save socket.io @types/socket.io @tsed/socketio
npm install --save-dev @tsed/socketio-testing
```
--------------------------------
### Configure Jest for TestContainers
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/mongoose.md
Configure Jest to use global setup and teardown files for starting and stopping the MongoDB server.
```ts
// jest.config.js
module.exports = {
globalSetup: ["jest.setup.js"],
globalTeardown: ["jest.teardown.js"]
};
// jest.setup.js
const {TestContainersMongo} = require("@tsed/testcontainers-mongo");
module.exports = async () => {
await TestContainersMongo.startMongoServer();
};
// jest.teardown.js
const {TestContainersMongo} = require("@tsed/testcontainers-mongo");
module.exports = async () => {
await TestContainersMongo.stopMongoServer();
};
```
--------------------------------
### Install graphql-subscriptions
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/graphql-ws.md
Install the graphql-subscriptions package using npm. This is the first step to enable subscription functionality.
```shell
npm install graphql-subscriptions
```
--------------------------------
### Install @tsedio/config-ioredis with bun
Source: https://github.com/tsedio/tsed/blob/production/packages/config/ioredis/readme.md
Install the package and its peer dependencies using bun.
```sh
bun add @tsedio/config-ioredis
bun add @tsed/config @tsed/ioredis ioredis
```
--------------------------------
### Jest Configuration for Testcontainers
Source: https://github.com/tsedio/tsed/blob/production/packages/testcontainers/mongo/readme.md
Configure Jest to use global setup and teardown files for starting and stopping the MongoDB server with Testcontainers.
```ts
// jest.config.js
module.exports = {
globalSetup: ["jest.setup.js"],
globalTeardown: ["jest.teardown.js"]
};
// jest.setup.js
const {TestContainersMongo} = require("@tsed/mongo");
module.exports = async () => {
await TestContainersMongo.startMongoServer();
};
// jest.teardown.js
const {TestContainersMongo} = require("@tsed/mongo");
module.exports = async () => {
await TestContainersMongo.stopMongoServer();
};
```
--------------------------------
### Get OpenSpec from Controller
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/model.md
Retrieve the OpenSpec from a Controller to generate the Swagger OpenSpec. This example shows a TypeScript controller and its corresponding OpenSpec JSON.
```typescript
import { Controller, Get, Route } from "@tsed/common";
@Controller("/my-controller")
export class MyController {
@Get("/users")
getUsers(): string {
return "Hello";
}
}
```
```json
{
"openapi": "3.0.0",
"paths": {
"/my-controller/users": {
"get": {
"operationId": "MyController_getUsers",
"responses": {
"200": {
"description": "Success"
}
}
}
}
}
}
```
--------------------------------
### Create a Client repository using OIRedisAdapter
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/adapters-ioredis.md
Demonstrates how to create a repository for Client models using the OIRedisAdapter with custom options like collectionName and keyPrefix.
```typescript
import {Adapter, Adapters, AdapterModel} from "@tsed/adapters";
import {Injectable} from "@tsed/di";
import {OIRedisAdapter} from "@tsed/adapters-ioredis";
import {Property} from "@tsed/schema";
class Client implements AdapterModel {
@Property()
_id: string;
@Property()
name: string;
@Property()
secret: string;
}
@Injectable()
export class ClientsRepository {
private store: Adapter;
constructor(private adapters: Adapters) {
this.store = this.adapters.invokeAdapter({
adapter: OIRedisAdapter,
collectionName: "client",
model: Client,
keyPrefix: "tests:e2e:run-42"
});
}
async createClient(input: Pick) {
return this.store.create(input);
}
async getClients() {
return this.store.findAll();
}
async getClientById(id: string) {
return this.store.findById(id);
}
async updateClient(id: string, patch: Partial) {
const current = await this.store.findById(id);
if (!current) {
return undefined;
}
return this.store.update(id, {...current, ...patch});
}
async deleteClient(id: string) {
return this.store.deleteById(id);
}
}
```
--------------------------------
### Start Ts.ED Project (bun)
Source: https://github.com/tsedio/tsed/blob/production/docs/getting-started.md
Run your Ts.ED project using bun after initialization. This command starts the development server.
```bash
bun start
```
--------------------------------
### Create Lambda Controller
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/platform-serverless-http.md
Define a controller for your serverless function. This example shows a basic controller for timeslots with GET requests and query parameters.
```typescript
import {Controller, Inject} from "@tsed/di";
import {Get, Returns, Summary} from "@tsed/schema";
import {QueryParams} from "@tsed/platform-params";
import {TimeslotsService} from "../services/TimeslotsService";
import {TimeslotModel} from "../models/TimeslotModel";
@Controller("/timeslots")
export class TimeslotsController {
@Inject()
protected timeslotsService: TimeslotsService;
@Get("/")
@Summary("Return a list of timeslots")
@(Returns(200, Array).Of(TimeslotModel))
get(@QueryParams("date_start") dateStart: Date, @QueryParams("date_end") dateEnd: Date) {
return this.timeslotsService.find({
dateStart,
dateEnd
});
}
}
```
--------------------------------
### Start Stripe CLI Listener
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/stripe.md
Use the Stripe CLI to listen for webhook events and retrieve your webhook signing secret. Ensure you have the stripe-cli installed.
```sh
stripe listen
> Ready! You are using Stripe API Version [2020-08-27]. Your webhook signing secret is whsec_*****************************
```
--------------------------------
### Get and Render String with Ejs Engine
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Retrieve a template engine using getEngine and render a template string directly. The Ejs engine is imported for this example.
```typescript
import {getEngine} from "@tsed/engines";
import "@tsed/engines/EjsEngine.js"; // or any other engine you want to use
getEngine("ejs")
.render("<%= user.name %>
")
.then((html) => {
console.log(html);
});
```
--------------------------------
### Start Ts.ED Project (npm)
Source: https://github.com/tsedio/tsed/blob/production/docs/getting-started.md
Run your Ts.ED project using npm after initialization. This command starts the development server.
```bash
npm start
```
--------------------------------
### Create a Simple Controller
Source: https://github.com/tsedio/tsed/blob/production/docs/introduction/cheat-sheet.md
Define a basic REST controller to handle incoming HTTP requests. This example shows a GET endpoint returning a JSON response.
```typescript
import {Controller} from "@tsed/di";
import {Get} from "@tsed/schema";
@Controller("/hello")
export class HelloController {
@Get("/")
get() {
return {message: "Hello world"};
}
}
```
--------------------------------
### Create a Custom Endpoint with Tsed Directus SDK
Source: https://github.com/tsedio/tsed/blob/production/packages/third-parties/directus-sdk/readme.md
Define a custom API endpoint using `defineEndpoint`. This example shows how to inject services and handle GET requests.
```typescript
import {defineEndpoint} from "@tsed/directus-sdk";
import {inject} from "@tsed/di";
export default defineEndpoint({
id: "my-api",
handler: (router) => {
router.get("/hello", async (req, res) => {
const myService = inject(MyService);
const result = await myService.doSomething();
return res.json(result);
});
}
});
```
--------------------------------
### Install @tsed/adapters-ioredis with bun
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/adapters-ioredis.md
Install the ioredis adapter package and its dependencies using bun.
```sh
bun add @tsed/adapters-ioredis @tsed
/ioredis ioredis
```
--------------------------------
### Install Socket.io with yarn
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/socket-io.md
Install the Socket.io module and its types using yarn.
```sh
yarn add socket.io @types/socket.io @tsed/socketio
yarn add --dev @tsed/socketio-testing
```
--------------------------------
### TLS Proxy Setup with Caddy
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/oidc.md
Configure Ts.ED to use a TLS offloading proxy. This example shows how to set `proxy: true` and run Caddy to forward requests.
```bash
caddy reverse-proxy --from localhost:8443 --to localhost:8083
```
--------------------------------
### Install MikroORM Packages (Yarn)
Source: https://github.com/tsedio/tsed/blob/production/packages/orm/mikro-orm/readme.md
Install the core MikroORM package along with the TS.ED integration and the specific database driver using Yarn.
```bash
yarn add @mikro-orm/core @tsed/mikro-orm @mikro-orm/mongodb # for mongo
```
```bash
yarn add @mikro-orm/core @tsed/mikro-orm @mikro-orm/mysql # for mysql/mariadb
```
```bash
yarn add @mikro-orm/core @tsed/mikro-orm @mikro-orm/mariadb # for mysql/mariadb
```
```bash
yarn add @mikro-orm/core @tsed/mikro-orm @mikro-orm/postgresql # for postgresql
```
```bash
yarn add @mikro-orm/core @tsed/mikro-orm @mikro-orm/sqlite # for sqlite
```
--------------------------------
### Basic Socket.IO Service Setup
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/socket-io.md
Example of a basic Socket.IO service configuration within a Tsed application. This service handles incoming socket connections and emits messages.
```typescript
import { SocketService, Socket, Args, Emit, SocketUseBefore, SocketUseAfter, SocketSession, SocketConnected, SocketDisconnected, SocketEvent, SocketRooms, SocketRouter, SocketNext, SocketRouterMethods, SocketRouterOptions, SocketSessionService, SocketServiceOptions, SocketMiddlewareError } from "@tsed/socketio";
import { Injectable } from "@tsed/di";
@Injectable()
export class MySocketService {
@SocketConnected()
onConnection(@Socket() socket: Socket) {
console.log("New connection established", socket.id);
}
@SocketDisconnected()
onDisconnection(@Socket() socket: Socket) {
console.log("Connection closed", socket.id);
}
@SocketEvent("message")
onMessage(@Args() args: any[], @Socket() socket: Socket) {
console.log(`Received message from ${socket.id}:`, args);
this.broadcast("chat message", { id: socket.id, message: args[0] });
}
@Emit("response")
async sendResponse(@Args() args: any[]) {
return args[0];
}
@SocketRooms()
async joinRoom(@Socket() socket: Socket, room: string) {
await socket.join(room);
return `Joined room ${room}`;
}
@SocketRouterMethods()
private router: SocketRouter;
@SocketRouter()
async getAllUsers(@Socket() socket: Socket) {
const users = await this.getUsersInRoom(socket.nsp.name);
return users;
}
private async getUsersInRoom(room: string) {
const connectedSockets = await this.io.of(room).fetchSockets();
return connectedSockets.map(s => s.id);
}
private get io() {
return this.socketService.getIO();
}
constructor(private socketService: SocketService) {}
}
```
--------------------------------
### Serve Documentation Locally
Source: https://github.com/tsedio/tsed/blob/production/docs/contributing.md
Start a local server to preview documentation changes. Ts.ED uses docsify for markdown conversion.
```bash
npm run doc:serve
```
--------------------------------
### MikroORM Controller with Transactional Decorator
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/mikroorm.md
Example of a Ts.ED controller using MikroORM's @Transactional decorator for create and get operations. Ensures atomicity for the create operation with retries.
```typescript
import {Post, Post, Get} from "@tsed/schema";
import {Controller, Inject} from "@tsed/di";
import {BodyParams} from "@tsed/platform-params";
import {Transactional} from "@tsed/mikro-orm";
@Controller("/users")
export class UsersCtrl {
@Inject()
private readonly usersService!: UsersService;
@Post("/")
@Transactional({retry: true})
create(@BodyParams() user: User): Promise {
return this.usersService.create(user);
}
@Get("/")
getList(): Promise {
return this.usersService.find();
}
}
```
--------------------------------
### Install Socket.io with pnpm
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/socket-io.md
Install the Socket.io module and its types using pnpm.
```sh
pnpm add socket.io @types/socket.io @tsed/socketio
pnpm add -D @tsed/socketio-testing
```
--------------------------------
### Original Discord Protocol JavaScript Example
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/passport.md
This JavaScript code demonstrates the original Discord passport strategy setup, including client ID, secret, callback URL, and scopes.
```javascript
const DiscordTokenStrategy = require('passport-discord').Strategy;
const Oauth2RefreshToken = require('passport-oauth2-refresh');
passport.use(new DiscordTokenStrategy({
clientID: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
callbackURL: 'http://localhost:3000/auth/discord/callback',
scope: ['identify', 'email']
}, (accessToken, refreshToken, profile, done) => {
// find or create user
User.findOrCreate(profile.id, (err, user) => {
return done(err, user);
});
}));
Oauth2RefreshToken.use(new Oauth2RefreshToken.Strategy({
passReqToCallback: true
}, async (req, refreshToken, params, done) => {
try {
const accessToken = await refresh(refreshToken);
req.session.passport.user.accessToken = accessToken;
done(null, accessToken);
} catch (err) {
done(err);
}
}));
```
--------------------------------
### Install Platform Serverless with Bun
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/platform-serverless.md
Install the necessary Ts.ED platform serverless package and related serverless tools using Bun. Also, install the types for AWS Lambda.
```bash
bun add @tsed/platform-serverless serverless serverless-offline
bun add -D @types/aws-lambda
```
--------------------------------
### TypeORM Unit Test with Testcontainers PostgreSQL
Source: https://github.com/tsedio/tsed/blob/production/docs/plugins/premium/testcontainers/postgres.md
Provides an example of a unit test using TypeORM with Testcontainers for PostgreSQL. It includes entity definition and test setup using PlatformTest.
```typescript
import {PlatformTest} from "@tsed/platform-http/testing";
import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";
import {TestContainersPostgres} from "@tsedio/testcontainers-postgres";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({unique: true})
email: string;
@Column()
name: string;
}
describe("User", () => {
beforeEach(() =>
PlatformTest.create({
typeorm: [
{
name: "default",
type: "postgres",
entities: [User],
synchronize: true,
...TestContainersPostgres.getPostgresOptions()
}
]
})
);
afterEach(async () => {
await TestContainersPostgres.reset(); // reset the database
await PlatformTest.reset();
});
it("should create a user", async () => {
const userRepository = PlatformTest.get(getRepository(User));
// GIVEN
const user = userRepository.create({
email: "test@test.com",
name: "Test User"
});
// WHEN
await userRepository.save(user);
// THEN
expect(user.id).toBeDefined();
});
});
```
--------------------------------
### Initialize Ts.ED Project with Prisma (bun)
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/prisma.md
Use this command to create a new Ts.ED project with Prisma integration using bun.
```sh
bunx -p @tsed/cli tsed init tsed-prisma
```
--------------------------------
### Install GraphQL WS with Npm
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/snippets/graphql/graphql-ws.md
Install the `@tsed/graphql-ws` and `graphql-ws` packages using npm.
```bash
npm install --save @tsed/graphql-ws graphql-ws
```
--------------------------------
### Test Lambda Controller with PlatformServerlessTest
Source: https://github.com/tsedio/tsed/blob/production/packages/platform/platform-serverless-http/readme.md
Example demonstrating how to test a Lambda controller using PlatformServerlessTest. It shows the necessary imports, controller definition, test setup with bootstrap, and request simulation.
```typescript
import {PlatformServerless} from "@tsed/platform-serverless-http";
import {PlatformServerlessTest} from "@tsed/platform-serverless-testing";
import {PlatformExpress} from "@tsed/platform-express";
import {Server} from "./Server.js";
@Controller("/timeslots")
class TimeslotsController {
@Get("/")
getAll() {
return [];
}
}
describe("TimeslotsController", () => {
beforeEach(
PlatformServerlessTest.bootstrap(PlatformServerlessHttp, {
server: Server,
mount: {
"/": [TimeslotsLambdaController]
}
})
);
afterEach(() => PlatformServerlessTest.reset());
it("should call getAll Lambda", async () => {
const response = await PlatformServerlessTest.request.get("/timeslots");
expect(response.statusCode).toEqual(200);
expect(JSON.parse(response.body)).toEqual([]);
});
});
```
--------------------------------
### Tsed ioredis Sentinel Configuration
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/ioredis.md
Configure ioredis for a Redis sentinel setup. This example demonstrates how to specify the sentinel master name and sentinel nodes, also allowing for cache integration.
```typescript
import {Configuration} from "@tsed/di";
import "@tsed/platform-cache"; // add this module if you want to use cache
import "@tsed/ioredis";
@Configuration({
ioredis: [
{
name: "default",
// share the Redis connection with @tsed/platform-cache
cache: true,
// sentinel master name
sentinelName: "redis-master",
// sentinels nodes
sentinels: ["..."],
redisOptions: {
noDelay: true,
connectTimeout: 15000,
autoResendUnfulfilledCommands: true,
maxRetriesPerRequest: 5,
enableAutoPipelining: true,
autoPipeliningIgnoredCommands: ["scan"]
}
//
}
],
// cache options
cache: {
ttl: 300
}
})
class MyModule {}
```
--------------------------------
### Serve Documentation Locally
Source: https://github.com/tsedio/tsed/blob/production/CONTRIBUTING.md
Run the Ts.ED documentation website locally using Vuepress. This command allows you to preview documentation changes before submitting them.
```bash
yarn vuepress:docs:serve
```
--------------------------------
### Tsed ioredis Cluster Configuration
Source: https://github.com/tsedio/tsed/blob/production/docs/tutorials/ioredis.md
Configure ioredis for a Redis cluster setup. This example shows how to specify cluster nodes and various cluster-specific options, including sharing the connection with @tsed/platform-cache.
```typescript
import {Configuration} from "@tsed/di";
import "@tsed/platform-cache"; // add this module if you want to use cache
import "@tsed/ioredis";
@Configuration({
ioredis: [
{
name: "default",
// share the Redis connection with @tsed/platform-cache
cache: true,
// cluster options
nodes: ["..."],
// other cluster options
scaleReads: "all",
maxRedirections: 16,
retryDelayOnTryAgain: 100,
retryDelayOnFailover: 200,
retryDelayOnClusterDown: 1000,
slotsRefreshTimeout: 15000,
slotsRefreshInterval: 20000,
enableOfflineQueue: true,
enableReadyCheck: true,
redisOptions: {
noDelay: true,
connectTimeout: 15000,
autoResendUnfulfilledCommands: true,
maxRetriesPerRequest: 5,
enableAutoPipelining: true,
autoPipeliningIgnoredCommands: ["scan"]
}
//
}
],
// cache options
cache: {
ttl: 300
}
})
class MyModule {}
```
--------------------------------
### Test Custom Keyword Validation
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/validation.md
Write unit tests to verify custom keyword validation logic. This example uses PlatformTest to get an Ajv instance and compile the schema generated by getJsonSchema.
```typescript
import "@tsed/ajv";
import {PlatformTest} from "@tsed/platform-http/testing";
import {getJsonSchema} from "@tsed/schema";
import {Product} from "./Product.js";
import "../keywords/RangeKeyword.js";
describe("Product", () => {
beforeEach(PlatformTest.create);
afterEach(PlatformTest.reset);
it("should call custom keyword validation (compile)", () => {
const ajv = PlatformTest.get(Ajv);
const schema = getJsonSchema(Product, {customKeys: true});
const validate = ajv.compile(schema);
expect(schema).to.deep.equal({
properties: {
price: {
exclusiveRange: true,
range: [10, 100],
type: "number"
}
},
type: "object"
});
expect(validate({price: 10.01})).toEqual(true);
expect(validate({price: 99.99})).toEqual(true);
expect(validate({price: 10})).toEqual(false);
expect(validate({price: 100})).toEqual(false);
});
});
```
--------------------------------
### Initialize Ts.ED Project with CLI (bun)
Source: https://github.com/tsedio/tsed/blob/production/docs/getting-started.md
Use the Ts.ED CLI to scaffold a new project with bun. This command uses bnx to install and run the CLI.
```bash
bnx -p @tsed/cli tsed init .
```
--------------------------------
### MikroORM Integration with Testcontainers Mongo
Source: https://github.com/tsedio/tsed/blob/production/docs/plugins/premium/testcontainers/mongo.md
Example demonstrating how to configure MikroORM with Testcontainers for MongoDB within a Ts.ED application's testing setup. Ensure TestContainersMongo is imported and used to retrieve MongoDB connection options.
```typescript
import {defineConfig} from "@mikro-orm/mongodb";
import {PlatformTest} from "@tsed/platform-http/testing";
import {TestContainersMongo} from "@tsedio/testcontainers-mongo";
beforeEach(async () => {
const mongoSettings = TestContainersMongo.getMongoOptions();
await PlatformTest.bootstrap(Server, {
disableComponentScan: true,
imports: [MikroOrmModule],
mikroOrm: [
defineConfig({
clientUrl: mongoSettings.url,
driverOptions: mongoSettings.connectionOptions,
entities: [User],
subscribers: [UnmanagedEventSubscriber1, new UnmanagedEventSubscriber2()]
})
]
});
});
```
--------------------------------
### Install Platform Fastify
Source: https://github.com/tsedio/tsed/blob/production/packages/platform/platform-fastify/readme.md
Install the @tsed/platform-fastify and fastify packages using npm or yarn.
```bash
npm install --save @tsed/platform-fastify fastify
```
--------------------------------
### Ts.ED Controller Example for User Resource
Source: https://github.com/tsedio/tsed/blob/production/packages/platform/common/readme.md
A basic controller to manage user resources using Ts.ED decorators for defining routes, parameters, and request bodies. It includes endpoints for getting, creating, updating, deleting, and finding users.
```typescript
import {Inject} from "@tsed/di";
import {Summary} from "@tsed/swagger";
import {
Returns,
ReturnsArray,
Controller,
Get,
QueryParams,
PathParams,
Delete,
Post,
Required,
BodyParams,
Status,
Put
} from "@tsed/schema";
import {BadRequest} from "@tsed/exceptions";
import {UsersService} from "../services/UsersService.js";
import {User} from "../models/User.js";
@Controller("/users")
export class UsersCtrl {
@Inject()
protected usersService: UsersService;
@Get("/:id")
@Summary("Get a user from his Id")
@Returns(User)
async getUser(@PathParams("id") id: string): Promise {
return this.usersService.findById(id);
}
@Post("/")
@Status(201)
@Summary("Create a new user")
@Returns(User)
async postUser(@Required() @BodyParams() user: User): Promise {
return this.usersService.save(user);
}
@Put("/:id")
@Status(201)
@Summary("Update the given user")
@Returns(User)
async putUser(@PathParams("id") id: string, @Required() @BodyParams() user: User): Promise {
if (user.id !== id) {
throw new BadRequest("ID mismatch with the given payload");
}
return this.usersService.save(user);
}
@Delete("/:id")
@Summary("Remove a user")
@Status(204)
async deleteUser(@PathParams("id") @Required() id: string): Promise {
await this.usersService.delete(user);
}
@Get("/")
@Summary("Get all users")
@ReturnsArray(User)
async findUser(@QueryParams("name") name: string) {
return this.usersService.find({name});
}
}
```
--------------------------------
### Install Platform Express.js
Source: https://github.com/tsedio/tsed/blob/production/packages/platform/platform-express/readme.md
Run this command to install the necessary packages for Platform Express.js and Express.js, along with their type definitions.
```bash
npm install --save @tsed/platform-express express
npm install --save-dev @types/express
```
--------------------------------
### Define a Job Processor Manually with Agenda
Source: https://github.com/tsedio/tsed/blob/production/packages/third-parties/agenda/readme.md
Manually define a job processor by injecting `Agenda` and `HttpClient`. This is useful for fetching data beforehand to dynamically build job names and options. The example shows how to define a `sendWelcomeEmail` job with concurrency and how to prepare jobs before Agenda starts and schedule them after.
```typescript
import {Define, JobsController} from "@tsed/agenda";
import {Agenda} from "agenda";
@JobsController({namespace: "email"})
export class EmailJobService {
@Inject()
agenda: Agenda;
@Inject()
httpClient: HttpClient;
cache: Map = new Map();
@Define({
name: "sendWelcomeEmail",
concurrency: 3
/* ... and any option you would normally pass to agenda.define(...) */
})
async sendWelcomeEmail(job: Job) {
// implement something here
console.log(job.attrs.data.locale);
}
async $beforeAgendaStart() {
const locales = await this.httpClient.get("/locales");
this.cache.set(
"sendWelcomeEmail",
locales.map((locale) => {
return this.agenda.create("sendWelcomeEmail", {locale});
})
);
}
async $afterAgendaStart() {
const jobs = this.cache.get("sendWelcomeEmail");
await Promise.all(jobs.map((job) => job.repeatEvery("1 week").save()));
}
}
```
--------------------------------
### Install dustjs-linkedin
Source: https://github.com/tsedio/tsed/blob/production/packages/engines/readme.md
Install dustjs-linkedin for the dust template engine. This will only be used if dustjs-helpers is not installed.
```sh
npm install dustjs-linkedin
```
--------------------------------
### Project Structure for a New Adapter
Source: https://github.com/tsedio/tsed/blob/production/docs/docs/platform-adapter.md
This is the recommended project structure for creating a new platform adapter. It includes directories for components, interfaces, services, and middlewares.
```text
platform-yourframework/
├── src/
│ ├── components/
│ │ └── PlatformYourFramework.ts
│ ├── interfaces/
│ │ └── PlatformYourFrameworkSettings.ts
│ ├── services/
│ │ ├── PlatformYourFrameworkHandler.ts
│ │ ├── PlatformYourFrameworkRequest.ts
│ │ └── PlatformYourFrameworkResponse.ts
│ ├── middlewares/
│ │ └── staticsMiddleware.ts
│ └── index.ts
└── package.json
```