How to use @tsed/common - 10 common examples

To help you get started, we’ve selected a few @tsed/common examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github TypedProject / ts-express-decorators / test / integration / app / controllers / calendars / CalendarCtrl.ts View on Github external
* By default, the response is sent with status 200 and is serialized in JSON.
   *
   * @param request
   * @param response
   * @returns {{id: any, name: string}}
   */
  @Get("/classic/:id")
  public findClassic(request: any, response: any): CalendarModel {
    const model = new CalendarModel();
    model.id = request.params.id;
    model.name = "test";

    return model;
  }

  @Get("/token")
  public getToken(@CookiesParams("authorization") authorization: string): string {
    if (authorization) {
      const token = this.tokenService.token();

      return token;
      // console.log('TOKEN', this.tokenService, token);
    }

    return "";
  }

  @Get("/token/:token")
  public updateToken(
    @PathParams("token")
    @Description("Token required to update token")
      token: string
github TypedProject / ts-express-decorators / src / servestatic / services / ServeStaticService.ts View on Github external
import * as Express from "express";
import {ServerSettingsService, Service, ExpressApplication} from "@tsed/common";

@Service()
export class ServeStaticService {
  constructor(@ExpressApplication private expressApp: Express.Application, private serverSettingsService: ServerSettingsService) {}

  $afterRoutesInit() {
    /* istanbul ignore else */
    if (require.resolve("serve-static")) {
      Object.keys(this.serverSettingsService.serveStatic).forEach(path => {
        [].concat(this.serverSettingsService.serveStatic[path] as any).forEach((directory: string) => this.mount(path, directory));
      });
    }
  }

  mount(path: string, directory: string) {
    const serveStatic = require("serve-static");
    const middleware = serveStatic(directory);
    this.expressApp.use(path, (request: any, response: any, next: any) => {
github TypedProject / ts-express-decorators / examples / passport-azure-ad / packages / server / src / Server.ts View on Github external
const rootDir = __dirname;
const clientDir = path.join(rootDir, "../../client/dist");
// In a local dev environment add these to a .env file (but don't commit it)
// In Azure add these as application settings
const {
  clientId = "clientID", // FIXME CHANGE THE default CLIENT_ID
  tenantId,
  UseScopeLevelAuth,
  Scopes
} = process.env;

const level: "info" | "warn" | "error" = "info";
// Application specific scopes.  Define in .env file if to use scopes and what the scopes are
const scopes = UseScopeLevelAuth === "true" ? Scopes.split(",") : null;
$log.info(`Scopes to use: ${scopes}`);

@ServerSettings({
  rootDir,
  acceptMimes: ["application/json"],
  port: process.env.PORT || "8081",
  httpsPort: false,
  logger: {
    debug: false,
    logRequest: true,
    requestFields: ["reqId", "method", "url", "headers", "query", "params", "duration"]
  },
  componentsScan: [
    `${rootDir}/protocols/**/*.ts`,
    `${rootDir}/services/**/*.ts`,
    `${rootDir}/middlewares/**/*.ts`,
    `${rootDir}/filters/**/*.ts`
github replicatedhq / kots / api / src / controllers / kots / KotsAPI.ts View on Github external
interface CreateAppBody {
  metadata: string;
}

interface UploadLicenseBody {
  name: string;
  license: string;
  appSlug: string;
}

interface UpdateAppBody {
  slug: string;
}

@Controller("/api/v1/kots")
export class KotsAPI {
  @Get("/ports")
  async kotsPorts(
    @Req() request: Request,
    @Res() response: Response,
  ): Promise {
    // This method is connected to over kubectl...
    // There is no user auth, but this method should be
    // exposed only on cluster ip to enforce that it's
    // not exposed to the public

    const kotsAppStore: KotsAppStore = request.app.locals.stores.kotsAppStore;

    const apps = await kotsAppStore.listInstalledKotsApps();
    if (apps.length === 0) {
      return [];
github TranBaVinhSon / microservice_nodejs_template / packages / api_gateway / src / index.ts View on Github external
async function bootstrap(): Promise {
  try {
    $log.debug("Start server...");
    const server = await ServerLoader.bootstrap(Server);

    await server.listen();
    $log.debug("Server initialized");
    Logger(); // hello, world
  } catch (er) {
    $log.error(er);
  }
}
github TranBaVinhSon / microservice_nodejs_template / packages / api_gateway / src / index.ts View on Github external
async function bootstrap(): Promise {
  try {
    $log.debug("Start server...");
    const server = await ServerLoader.bootstrap(Server);

    await server.listen();
    $log.debug("Server initialized");
    Logger(); // hello, world
  } catch (er) {
    $log.error(er);
  }
}
github replicatedhq / kots / api / src / controllers / ship / GitHubHookAPI.ts View on Github external
import WebhooksApi from "@octokit/webhooks";
import jwt from "jsonwebtoken";
import { Cluster } from "../../cluster";
import { Watch } from "../../watch"
import * as _ from "lodash";

interface ErrorResponse {
  error: {};
}

/**
 *  gets hooks from github
 */
@Controller("api/v1/hooks/github")
export class GitHubHookAPI {
  @Post("")
  async githubHook(
    @Res() response: Express.Response,
    @Req() request: Express.Request,
    @HeaderParams("x-github-event") eventType: string,
    @BodyParams("") body?: { action?: string }, // we're just gonna cast this later
  ): Promise<{} | ErrorResponse> {
    logger.info({msg: `received github hook for eventType ${eventType}`});

    switch (eventType) {
      case "pull_request": {
        await this.handlePullRequest(request, body as WebhooksApi.WebhookPayloadPullRequest);
        await this.createGithubCheck(request, body as WebhooksApi.WebhookPayloadPullRequest);
        response.status(204);
        return {};
      }
github replicatedhq / kots / api / src / controllers / kots / KotsAPI.ts View on Github external
} catch(err) {
        await request.app.locals.stores.kotsAppStore.setUpdateDownloadStatus(String(err), "failed");
        throw err;
      } finally {
        liveness.stop();
      }
    }
    downloadUpdates(); // download asyncronously

    response.status(200);
    return {
      updatesAvailable: updatesAvailable.length,
    };
  }

  @Post("/license")
  async kotsUploadLicense(
    @BodyParams("") body: UploadLicenseBody,
    @Req() request: Request,
    @Res() response: Response,
    @HeaderParams("Authorization") auth: string,
  ): Promise {

    // Intentionally not processing registry settings here because empty strings don't
    // necessarily mean existing info should be deleted.

    const session: Session = await request.app.locals.stores.sessionStore.decode(auth);
    if (!session || !session.userId) {
      response.status(401);
      return {};
    }
github replicatedhq / kots / kotsadm / api / src / controllers / troubleshoot / TroubleshootAPI.ts View on Github external
// Check if bundle exists
    const exists = await stores.troubleshootStore.supportBundleExists(supportBundleId);
    if (!exists) {
      response.send(404, "Bundle does not exist");
      return;
    }

    const b = await stores.troubleshootStore.getSupportBundle(supportBundleId);
    const analyzers = await stores.troubleshootStore.tryGetAnalyzersForKotsApp(b.watchId);
    await performAnalysis(supportBundleId, analyzers, stores);
    const analyzedBundle = await stores.troubleshootStore.getSupportBundle(supportBundleId);

    response.send(200, analyzedBundle);
  }

  @Post("/:watchId/:supportBundleId")
  public async bundleUploaded(
    @Res() response: Response,
    @Req() request: Request,
    @BodyParams("") body: BundleUploadedBody,
    @PathParams("watchId") watchId: string,
    @PathParams("supportBundleId") supportBundleId: string,
  ): Promise {
    const stores = request.app.locals.stores;

    // Don't create support bundle if there is one with the same ID
    const exists = await stores.troubleshootStore.supportBundleExists(supportBundleId);
    if (exists) {
      response.send(403);
      return;
    }
github TypedProject / ts-express-decorators / packages / socketio / src / services / SocketIOService.ts View on Github external
ServerSettingsService,
  Service,
  Constant
} from "@tsed/common";
import {nameOf} from "@tsed/core";
import * as SocketIO from "socket.io"; // tslint:disable-line: no-unused-variable
import {$log} from "ts-log-debug";
import {SocketHandlersBuilder} from "../class/SocketHandlersBuilder";
import {IO} from "../decorators/io";
import {ISocketProviderMetadata} from "../interfaces/ISocketProviderMetadata";
import {PROVIDER_TYPE_SOCKET_SERVICE} from "../registries/SocketServiceRegistry";

/**
 *
 */
@Service()
export class SocketIOService implements OnServerReady {
  @Constant("logger.disableRoutesSummary", false)
  disableRoutesSummary: boolean;

  /**
   *
   * @type {Map}
   */
  private namespaces: Map = new Map();

  constructor(
    private injector: InjectorService,
    @Inject(HttpServer) private httpServer: HttpServer,
    @Inject(HttpsServer) private httpsServer: HttpsServer,
    @IO private io: SocketIO.Server,
    private serverSettingsService: ServerSettingsService,