express#Application TypeScript Examples

The following examples show how to use express#Application. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: rsa_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
public static mount(app: Application, middleware: any[]) {
        app.post('/rsa/initialize', ...middleware, authInContainer('read', 'data'), this.init);

        app.post('/rsa/verify', ...middleware, authInContainer('read', 'data'), this.verify);

        app.post('/rsa/status', ...middleware, authInContainer('read', 'data'), this.status);

        app.post('/rsa/cancel', ...middleware, authInContainer('read', 'data'), this.cancel);
    }
Example #2
Source File: files.service.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
register(httpAdapter: AbstractHttpAdapter): void {
        if (!httpAdapter) {
            return;
        }

        const app: Application = httpAdapter.getInstance();

        app.get(`${FILES_BASE_ENDPOINT}/:fileToken/:fileName`, async (req, res): Promise<void> => {
            const {fileToken} = req.params;

            try {
                const {projectName, directory, name} = await TokenService.verify(fileToken);
                const environment = await this.systemProvider.getEnvironment();
                const project = await environment.projects.get(projectName);

                res.sendFile(path.join(project.root, directory, name));
            } catch (e) {
                res.sendStatus(404);
            }
        });
    }
Example #3
Source File: metatype_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
public static mount(app: Application, middleware: any[]) {
        app.post('/containers/:containerID/metatypes', ...middleware, authInContainer('write', 'ontology'), this.createMetatype);
        app.get('/containers/:containerID/metatypes/:metatypeID', ...middleware, authInContainer('read', 'ontology'), this.retrieveMetatype);
        app.get('/containers/:containerID/metatypes', ...middleware, authInContainer('read', 'ontology'), this.listMetatypes);
        app.put('/containers/:containerID/metatypes/:metatypeID', ...middleware, authInContainer('write', 'ontology'), this.updateMetatype);
        app.delete('/containers/:containerID/metatypes/:metatypeID', ...middleware, authInContainer('write', 'ontology'), this.archiveMetatype);

        app.post('/containers/:containerID/metatypes/:metatypeID', ...middleware, authInContainer('read', 'ontology'), this.validateProperties);
    }
Example #4
Source File: setupDev.ts    From graphql-schema-registry with MIT License 6 votes vote down vote up
export default async function setupDev(app: Application) {
	const { default: webpackConfig } = await import(WEBPACK_FILE_LOCATION);
	const compiler = webpack(webpackConfig as webpack.Configuration);
	app.use(
		webpackDevMiddleware(compiler, {
			writeToDisk: true,
			publicPath: webpackConfig.output.publicPath,
		})
	);

	app.use(
		//  `webpack-hot-middleware` currently does not work reliably with Webpack 5:
		//  Ref: https://github.com/webpack-contrib/webpack-hot-middleware/pull/397
		webpackHotMiddleware(compiler, {
			log: false,
			path: `/__webpack_hmr`,
			heartbeat: 10 * 1000,
		})
	);
}
Example #5
Source File: graph_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
public static mount(app: Application, middleware: any[]) {
        app.post('/containers/:containerID/graphs/nodes/', ...middleware, authInContainer('write', 'data'), this.createOrUpdateNodes);
        app.get('/containers/:containerID/graphs/nodes/metatype/:metatypeID', ...middleware, authInContainer('read', 'data'), this.listNodesByMetatypeID);
        app.get('/containers/:containerID/graphs/nodes/', ...middleware, authInContainer('read', 'data'), this.listNodes);
        app.get('/containers/:containerID/graphs/nodes/:nodeID', ...middleware, authInContainer('read', 'data'), this.retrieveNode);

        // This should return a node and all connected nodes and connecting edges for n layers.
        app.get('/containers/:containerID/graphs/nodes/:nodeID/graph', ...middleware, authInContainer('read', 'data'), this.retrieveNthNodes);

        app.post('/containers/:containerID/graphs/nodes/:nodeID/timeseries', ...middleware, authInContainer('read', 'data'), this.queryTimeseriesData);
        app.get('/containers/:containerID/graphs/nodes/:nodeID/timeseries', ...middleware, authInContainer('read', 'data'), this.queryTimeseriesDataTypes);

        app.get('/containers/:containerID/graphs/nodes/:nodeID/files', ...middleware, authInContainer('read', 'data'), this.listFilesForNode);
        app.put('/containers/:containerID/graphs/nodes/:nodeID/files/:fileID', ...middleware, authInContainer('write', 'data'), this.attachFileToNode);
        app.delete('/containers/:containerID/graphs/nodes/:nodeID/files/:fileID', ...middleware, authInContainer('write', 'data'), this.detachFileFromNode);

        app.post('/containers/:containerID/graphs/edges/', ...middleware, authInContainer('write', 'data'), this.createOrUpdateEdges);
        app.get('/containers/:containerID/graphs/edges/:edgeID', ...middleware, authInContainer('read', 'data'), this.retrieveEdge);
        app.get('/containers/:containerID/graphs/edges/', ...middleware, authInContainer('read', 'data'), this.listEdges);

        app.get('/containers/:containerID/graphs/edges/:edgeID/files', ...middleware, authInContainer('read', 'data'), this.listFilesForEdge);
        app.put('/containers/:containerID/graphs/edges/:edgeID/files/:fileID', ...middleware, authInContainer('write', 'data'), this.attachFileToEdge);
        app.delete('/containers/:containerID/graphs/edges/:edgeID/files/:fileID', ...middleware, authInContainer('write', 'data'), this.detachFileFromEdge);

        app.delete('/containers/:containerID/graphs/nodes/:nodeID', ...middleware, authInContainer('write', 'data'), this.deleteNode);
        app.delete('/containers/:containerID/graphs/edges/:edgeID', ...middleware, authInContainer('write', 'data'), this.archiveEdge);
    }
Example #6
Source File: auth.service.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
register(httpAdapter: AbstractHttpAdapter): void {
        if (!httpAdapter) {
            return;
        }

        const app: Application = httpAdapter.getInstance();

        this.registerAuthenticationHandlers(app);
    }
Example #7
Source File: swagger.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
function addSwaggerMiddlewares(app: Application): void {
  app.use(
    swaggerStats.getMiddleware({
      name: "Monkeytype API",
      uriPath: "/stats",
      authentication: process.env.MODE !== "dev",
      apdexThreshold: 100,
      swaggerSpec: internalSwaggerSpec,
      onAuthenticate: (_req, username, password) => {
        return (
          username === process.env.STATS_USERNAME &&
          password === process.env.STATS_PASSWORD
        );
      },
      onResponseFinish: (_req, res, rrr) => {
        //@ts-ignore ignored because monkeyMessage doesnt exist in response
        rrr.http.response.message = res.monkeyMessage;
        if (process.env.MODE === "dev") {
          return;
        }
        const authHeader = rrr.http.request.headers?.authorization ?? "None";
        const authType = authHeader.split(" ");
        _.set(rrr.http.request, "headers.authorization", authType[0]);
        _.set(rrr.http.request, "headers['x-forwarded-for']", "");
      },
    })
  );

  app.use(
    ["/documentation", "/docs"],
    swaggerUi.serve,
    swaggerUi.setup(publicSwaggerSpec, SWAGGER_UI_OPTIONS)
  );
}
Example #8
Source File: server.ts    From TypeScript-in-Nodejs-Starter with MIT License 6 votes vote down vote up
/**
 * Adds a set of middleware only if the app runs on the production machine.
 * @param app The express application to add the set of production middleware to it.
 */
function setupProduction(app: Application): void {
  /* Only if the app runs on the production machine. */
  if (process.env.NODE_ENV === 'production') {
    /* Helmet helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help! */
    app.use(helmet());

    /* Gzip compressing can greatly decrease the size of the response body and hence increase the speed of a web app.
     * Use the compression middleware for gzip compression in your Express app.
     */
    app.use(compression());
  }
}
Example #9
Source File: social-auth.service.ts    From nestjs-angular-starter with MIT License 6 votes vote down vote up
constructor(
    @Inject('SOCIAL_AUTH_MODULE_CONFIG') private config: SocialAuthModuleConfig,
    adapterHost: HttpAdapterHost,
  ) {
    // Don't do anything on test as there is not instance of express
    if (appConfig.ENVIRONMENT === 'test') return;

    let expressApp: Application;

    try {
      // Get the express app in order to initialize social authentication
      expressApp = adapterHost.httpAdapter.getInstance() as Application;
    } catch (error) {
      // Fail with an error but continue
      Logger.error(error);
    }

    if (!expressApp)
      // TODO: This should throw an error instead
      Logger.warn(
        "Social authentication is not supported, couldn't get handle of express!",
      );
    else {
      // Now initialize the social authentication
      this.init(expressApp);
    }
  }
Example #10
Source File: index.ts    From lighthouse-audit-service with Apache License 2.0 6 votes vote down vote up
function configureMiddleware(
  app: Application,
  options: LighthouseAuditServiceOptions,
) {
  if (options.cors) {
    app.use(corsMiddleware());
  }
  app.use(compression());
  app.use(bodyParser.json());
  app.use(
    morgan('combined', {
      stream: {
        write(message: String) {
          logger.info(message);
        },
      },
    }),
  );
}
Example #11
Source File: server.ts    From TypeScript-in-Nodejs-Starter with MIT License 6 votes vote down vote up
/**
 * Sets the http-request options for an express server.
 * @param app The express application to set its express server's request options.
 */
function setRequestOptions(app: Application): void {
  /**
   * Enable CORS to allow any javascript client to consume your server's api.
   */
  app.use(cors());

  /**
   * Allow parse incoming requests as JSON payloads.
   * The limit of request body size my be set using this option { limit: '5mb' }, default is 100kb.
   */
  app.use(express.json());

  /**
   * Allow parse incoming urlencoded requests bodies.
   * The limit of request body size my be set using this option { limit: '5mb' }, default is 100kb.
   */
  app.use(express.urlencoded({ extended: true }));
}
Example #12
Source File: index.ts    From lighthouse-audit-service with Apache License 2.0 6 votes vote down vote up
export function configureErrorMiddleware(app: Application) {
  /* eslint-disable @typescript-eslint/no-unused-vars */
  app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
    /* eslint-enable @typescript-eslint/no-unused-vars */
    if (err instanceof StatusCodeError) res.status(err.statusCode);
    else res.status(500);
    res.send(err.message);
  });
}
Example #13
Source File: oauth_routes.ts    From Deep-Lynx with MIT License 6 votes vote down vote up
public static mount(app: Application, middleware: any[]) {
        // OAuth application management
        app.get('/oauth/applications/create', csurf(), ...middleware, LocalAuthMiddleware, this.createOAuthApplicationPage);
        app.post('/oauth/applications', csurf(), ...middleware, LocalAuthMiddleware, this.createOAuthApplication);
        app.get('/oauth/applications', csurf(), ...middleware, LocalAuthMiddleware, this.listOAuthApplications);
        app.get('/oauth/applications/:oauthAppID', ...middleware, csurf(), LocalAuthMiddleware, this.oauthApplicationPage);
        app.put('/oauth/applications/:oauthAppID', ...middleware, csurf(), LocalAuthMiddleware, this.updateOAuthApplication);
        app.delete('/oauth/applications/:oauthAppID', ...middleware, csurf(), LocalAuthMiddleware, this.deleteOAuthApplication);

        // login, register and authorize
        app.get('/oauth', csurf(), this.loginPage);
        app.get('/logout', this.logout);
        app.post('/oauth', csurf(), LocalAuthMiddleware, this.login);

        // saml specific
        app.get('/login-saml', this.loginSaml);
        app.post('/oauth/saml', this.saml);

        app.get('/oauth/register', csurf(), this.registerPage);
        app.post('/oauth/register', csurf(), this.createNewUser);

        app.get('/oauth/authorize', csurf(), LocalAuthMiddleware, this.authorizePage);
        app.post('/oauth/authorize', csurf(), LocalAuthMiddleware, this.authorize);
        app.post('/oauth/exchange', this.tokenExchange);
        app.get('/oauth/token', this.getToken);

        // profile management and email validation/reset password
        app.get('/oauth/profile', csurf(), LocalAuthMiddleware, this.profile);
        app.post('/oauth/profile/keys', csurf(), LocalAuthMiddleware, this.generateKeyPair);
        app.delete('/oauth/profile/keys/:keyID', csurf(), LocalAuthMiddleware, this.deleteKeyPair);

        app.get('/validate-email', this.validateEmail);

        app.get('/reset-password', csurf(), this.resetPasswordPage);
        app.post('/reset-password', csurf(), this.initiatePasswordReset);
        app.post('/reset-password/reset', csurf(), this.resetPassword);
    }
Example #14
Source File: bootstrap.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
bootstrapApp = async (): Promise<BootstrapSettings> => {
    const framework = await bootstrapMicroframework({
        loaders: [
            winstonLoader,
            iocLoader,
            eventDispatchLoader,
            typeormLoader,
            expressLoader,
            homeLoader,
        ],
    });
    return {
        app: framework.settings.getData('express_app') as Application,
        server: framework.settings.getData('express_server') as http.Server,
        connection: framework.settings.getData('connection') as Connection,
    } as BootstrapSettings;
}
Example #15
Source File: app.ts    From kfp-tekton-backend with Apache License 2.0 6 votes vote down vote up
function getRegisterHandler(app: Application, basePath: string) {
  return (
    func: (name: string | string[], handler: express.Handler) => express.Application,
    route: string | string[],
    handler: express.Handler,
  ) => {
    func.call(app, route, handler);
    return func.call(app, `${basePath}${route}`, handler);
  };
}
Example #16
Source File: index.ts    From tinyhouse with MIT License 6 votes vote down vote up
async function mount(app: Application) {
    const db = await connectDatabase();

    app.use(cookieParser(process.env.SECRET));

    const server = new ApolloServer({
        typeDefs,
        resolvers,
        context: ({ req, res }) => ({ db, req, res }),
    });
    await server.start();
    server.applyMiddleware({ app, path: "/api" });

    app.listen(port);

    console.log(`[app]: http://localhost:${port}`);
}
Example #17
Source File: server.ts    From TypeScript-in-Nodejs-Starter with MIT License 6 votes vote down vote up
/**
 * Setups an express server on top of the provided instance of express application.
 * @param app The express application that will be used to setup an express server.
 */
export function setupServer(app: Application): void {
  /**
   * The order matters.
   * 1. Setup production middleware.
   * 2. Set request options.
   * 3. Register routes.
   * 4. Add the error-handler middleware at the very end of pipeline.
   */
  setupProduction(app);
  setRequestOptions(app);
  registerRoutes(app);
  app.use(errorHandler);
}
Example #18
Source File: app.ts    From expresso with MIT License 5 votes vote down vote up
private readonly application: Application
Example #19
Source File: Container.ts    From pdf-generator-service with MIT License 5 votes vote down vote up
public static async factory(app: Application): Promise<Container> {
    const container = new Container(app)
    await wire(container)
    return container
  }
Example #20
Source File: auth.service.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
registerAuthenticationHandlers(app: Application): void {
        app.get(AUTHENTICATION_ENDPOINT, async (req, res): Promise<void> => {
            const environment = await this.systemProvider.getEnvironment();
            const redirectTo = Str.from(req.query.redirectTo).toString();

            try {
                const {authUrl} = await environment.login(redirectTo);

                res.redirect(authUrl);
            } catch (e) {
                res.status(403);
                res.send(e.message);
            }
        });

        app.get(VALIDATION_ENDPOINT, async (req, res): Promise<void> => {
            const queryObject = req.query;

            if (queryObject.error) {
                res.status(401);
                res.send(`Login failed: ${queryObject.error}`);
                return;
            }

            try {
                const environment = await this.systemProvider.getEnvironment();
                const authToken = await environment.generateAuthToken(queryObject);

                // @todo: use signed cookies
                res.cookie(AUTH_TOKEN_HEADER, authToken);
                res.header(AUTH_TOKEN_HEADER, authToken);

                // @todo: this is Google OAuth specific
                if (queryObject.state) {
                    const state = Str.from(queryObject.state).toString();
                    res.redirect(getAuthRedirect(environment.httpOrigin, state, authToken));
                    return;
                }

                res.status(201);
                res.send('You are authenticated, you can close this tab now.');
            } catch (e) {
                res.status(403);
                res.send(e.message);
            }
        });

        app.get(VERIFICATION_ENDPOINT, async (req, res): Promise<void> => {
            const authToken = getRequestToken(req, AUTH_TOKEN_HEADER);
            const environment = await this.systemProvider.getEnvironment();

            try {
                await environment.verifyAuthToken(authToken);
                res.sendStatus(200);
            } catch (e) {
                res.clearCookie(AUTH_TOKEN_HEADER);
                res.status(403);
                res.send(e.message);
            }
        });
    }
Example #21
Source File: index.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
function addApiRoutes(app: Application): void {
  app.get("/leaderboard", (_req, res) => {
    res.sendStatus(404);
  });

  addSwaggerMiddlewares(app);

  app.use(
    (req: MonkeyTypes.Request, res: Response, next: NextFunction): void => {
      const inMaintenance =
        process.env.MAINTENANCE === "true" || req.ctx.configuration.maintenance;

      if (inMaintenance) {
        res.status(503).json({ message: "Server is down for maintenance" });
        return;
      }

      if (req.path === "/psas") {
        const clientVersion = req.headers["client-version"];
        recordClientVersion(clientVersion?.toString() ?? "unknown");
      }

      next();
    }
  );

  app.get(
    "/",
    asyncHandler(async (_req, _res) => {
      return new MonkeyResponse("ok", {
        uptime: Date.now() - APP_START_TIME,
        version,
      });
    })
  );

  app.get("/psa", (_req, res) => {
    res.json([
      {
        message:
          "It seems like your client version is very out of date as you're requesting an API endpoint that no longer exists. This will likely cause most of the website to not function correctly. Please clear your cache, or contact support if this message persists.",
        sticky: true,
      },
    ]);
  });

  _.each(API_ROUTE_MAP, (router: Router, route) => {
    const apiRoute = `${BASE_ROUTE}${route}`;
    app.use(apiRoute, router);
  });

  app.use(
    asyncHandler(async (req, _res) => {
      return new MonkeyResponse(
        `Unknown request URL (${req.method}: ${req.path})`,
        null,
        404
      );
    })
  );
}
Example #22
Source File: setup-routes.ts    From clean-architecture-api-boilerplate with MIT License 5 votes vote down vote up
setupRoutes = (app: Application): void => {
  app.use('/users', rateLimiter, userRoutes);
  app.use('/sign-in', rateLimiter, signInRoutes);
  app.use('/refresh-token', rateLimiter, refreshTokenRoutes);
}
Example #23
Source File: web.module.ts    From relate with GNU General Public License v3.0 5 votes vote down vote up
onModuleInit(): void {
        if (!this.httpAdapterHost) {
            return;
        }

        const {httpAdapter} = this.httpAdapterHost;
        const app: Application = httpAdapter.getInstance();
        const {schema} = this.schemaHost;
        const openApi = OpenAPI({
            schema,
            info: {
                title: 'Relate REST API',
                version: '1.0.0',
            },
        });

        // add multer to file upload endpoints
        const uploads = multer({dest: envPaths().tmp});

        app.use('/api/add-project-file', uploads.single('fileUpload'), (req, _, next) => {
            req.body = {
                ...req.body,
                fileUpload: {
                    // convert multer file object to the same shape as graphql-upload
                    ...req.file,
                    filename: req.file.originalname,
                },
            };
            next();
        });

        // convert GraphQL API to REST using SOFA
        app.use(
            '/api',
            useSofa({
                basePath: '/api',
                schema,
                onRoute(info) {
                    openApi.addRoute(info, {
                        basePath: '/api',
                    });
                },
            }),
        );

        // add Swagger page for REST API
        const openApiDefinitions = openApi.get();
        openApiDefinitions.paths['/api/add-project-file'] = fixAddProjectFilesOpenAPIDef(
            openApiDefinitions.paths['/api/add-project-file'],
        );

        app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(openApiDefinitions));
    }
Example #24
Source File: server.ts    From server with MIT License 5 votes vote down vote up
app: Application = express()
Example #25
Source File: BaseApi.ts    From node-boilerplate with Apache License 2.0 5 votes vote down vote up
public abstract register(express: Application): void;
Example #26
Source File: social-auth.service.ts    From nestjs-angular-starter with MIT License 5 votes vote down vote up
private init(express: Application): void {
    express.use(passport.initialize());
    this.initFacebook();
    this.initGoogle();
  }
Example #27
Source File: expressLoader.ts    From spurtcommerce with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
expressLoader: MicroframeworkLoader = (settings: MicroframeworkSettings | undefined) => {
    if (settings) {
        const connection = settings.getData('connection');

        /**
         * We create a new express server instance.
         * We could have also use useExpressServer here to attach controllers to an existing express instance.
         */
        const app = express();
        app.use(bodyParser.urlencoded({extended: true}));
        app.use(bodyParser.json({limit: '50mb'}));
        const expressApp: Application = useExpressServer(app, {
            cors: true,
            classTransformer: true,
            routePrefix: env.app.routePrefix,
            defaultErrorHandler: false,
            /**
             * We can add options about how routing-controllers should configure itself.
             * Here we specify what controllers should be registered in our express server.
             */
            controllers: env.app.dirs.controllers,
            middlewares: env.app.dirs.middlewares,
            interceptors: env.app.dirs.interceptors,

            /**
             * Authorization features
             */
            authorizationChecker: authorizationChecker(connection),
            currentUserChecker: currentUserChecker(connection),
        });

        // // parse application/x-www-form-urlencoded
        // expressApp.use(bodyParser.urlencoded({extended: true}));
        // expressApp.use(bodyParser.json({limit: '50mb'}));

        // Run application to listen on given port
        if (!env.isTest) {
            const server = expressApp.listen(env.app.port);
            settings.setData('express_server', server);
        }

        // Here we can set the data for other loaders
        settings.setData('express_app', expressApp);
    }
}
Example #28
Source File: ExpressReceiver.d.ts    From flect-chime-sdk-demo with Apache License 2.0 5 votes vote down vote up
app: Application;
Example #29
Source File: server.ts    From xrp-api with MIT License 5 votes vote down vote up
public expressApp(): Application {
    return this.app;
  }