express#Express TypeScript Examples
The following examples show how to use
express#Express.
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: routing.ts From express-zod-api with MIT License | 6 votes |
initRouting = ({
app,
logger,
config,
routing,
}: {
app: Express;
logger: Logger;
config: CommonConfig;
routing: Routing;
}) => {
if (config.startupLogo !== false) {
console.log(getStartupLogo());
}
routingCycle({
routing,
cors: config.cors,
endpointCb: (endpoint, path, method) => {
app[method](path, async (request, response) => {
logger.info(`${request.method}: ${path}`);
await endpoint.execute({ request, response, logger, config });
});
},
staticCb: (path, handler) => {
app.use(path, handler);
},
});
}
Example #2
Source File: graphql.ts From OpenVolunteerPlatform with MIT License | 6 votes |
createApolloServer = async function (app: Express, config: Config) {
const db = await connect(config);
const modelDefs = loadSchemaSync(resolve(__dirname, '../model/main.graphql'), {
loaders: [
new GraphQLFileLoader()
]
})
const { typeDefs, resolvers, contextCreator } = buildGraphbackAPI(modelDefs, {
serviceCreator: createKeycloakCRUDService(authConfig),
dataProviderCreator: createMongoDbProvider(db)
});
// TODO enable custom resolvers
const mergedResolvers: any = GMR.merge([resolvers, customResolvers]);
let apolloConfig: ApolloServerExpressConfig = {
typeDefs: typeDefs,
resolvers: mergedResolvers,
playground: true,
context: (context) => {
return {
...contextCreator(context),
db: db
}
}
}
if (config.keycloakConfig) {
apolloConfig = buildKeycloakApolloConfig(app, apolloConfig)
}
const apolloServer = new ApolloServer(apolloConfig)
apolloServer.applyMiddleware({ app });
return apolloServer;
}
Example #3
Source File: middleware.ts From snip with MIT License | 6 votes |
static registerMiddleware(app: Express): void {
app.enable('trust proxy');
app.disable('view cache');
app.use(
'/api/v1',
// 20 requests per 10 seconds
ratelimit({
windowMs: 10 * 1000,
max: 20,
}),
);
coreMiddlewares.forEach((middleware) => {
app.use(middleware);
});
}
Example #4
Source File: GithubCreateAppServer.ts From backstage with Apache License 2.0 | 6 votes |
private async listen(app: Express) {
return new Promise<string>((resolve, reject) => {
const listener = app.listen(0, () => {
const info = listener.address();
if (typeof info !== 'object' || info === null) {
reject(new Error(`Unexpected listener info '${info}'`));
return;
}
const { port } = info;
resolve(`http://localhost:${port}`);
});
});
}
Example #5
Source File: endpoint.ts From ens-metadata-service with MIT License | 6 votes |
export default function (app: Express) {
// #swagger.ignore = true
app.get('/', (_req, res) => {
res.send('Well done mate To see more go to "/docs"!');
});
app.get(
'/:networkName/:contractAddress(0x[a-fA-F0-9]{40})/:tokenId',
ensMetadata
);
app.get(
'/:networkName/:contractAddress(0x[a-fA-F0-9]{40})/:tokenId/image',
ensImage
);
app.get(
'/:networkName/:contractAddress(0x[a-fA-F0-9]{40})/:tokenId/rasterize',
ensRasterize
);
app.get('/:networkName/avatar/:name/meta', avatarMetadata);
app.get('/:networkName/avatar/:name', avatarImage);
app.get('/queryNFT', queryNFTep);
}
Example #6
Source File: index.ts From common-ts with MIT License | 6 votes |
secureExpressApp = (app: Express): void => {
// This is meant to provide some security across a wide range of
// attacks. It is mentioned in the express docs under
// Production Best Practices: Security
// https://expressjs.com/en/advanced/best-practice-security.html
// It's not entirely clear that this is helpful
app.use(helmet())
// Fix a known bad
app.use(rejectBadHeaders)
}
Example #7
Source File: cosmosProxy.ts From commonwealth with GNU General Public License v3.0 | 6 votes |
function setupCosmosProxy(app: Express, models: DB) {
// using bodyParser here because cosmjs generates text/plain type headers
app.post('/cosmosAPI/:chain', bodyParser.text(), async function cosmosProxy(req, res, next) {
log.trace(`Got request: ${JSON.stringify(req.body, null, 2)}`)
try {
log.trace(`Querying cosmos endpoint for chain: ${req.params.chain}`);
const chain = await models.Chain.findOne({
where: { id: req.params.chain },
include: models.ChainNode
});
if (!chain) {
throw new Error('Invalid chain');
}
log.trace(`Found cosmos endpoint: ${chain.ChainNode.url}`);
const response = await axios.post(chain.ChainNode.url, req.body, {
headers: {
origin: 'https://commonwealth.im'
}
});
log.trace(`Got response from endpoint: ${JSON.stringify(response.data, null, 2)}`);
return res.send(response.data);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
}
Example #8
Source File: setup-async-errors.ts From clean-architecture-api-boilerplate with MIT License | 6 votes |
setupAsyncErrors = (app: Express): void => {
app.use((error: Error, req: Request, res: Response, next: NextFunction) => {
/* istanbul ignore next */
if (!error) {
return next();
}
/* istanbul ignore next */
if (process.env.DEBUG === '1') {
console.error(error);
}
if (!(error instanceof DefaultApplicationError)) {
return res.status(500).json({
error: error.name,
message: 'Something went wrong',
statusCode: 500,
messages: ['Something went wrong'],
});
}
return res.status(error.statusCode).json({
error: error.name,
message: error.message,
statusCode: error.statusCode,
messages: error.messages,
});
});
}
Example #9
Source File: bind.ts From homebridge-zigbee-nt with Apache License 2.0 | 6 votes |
export function mapBindRoutes(express: Express, platform: ZigbeeNTHomebridgePlatform): void {
express.post<string, any, BindUnbindResponse, BindUnbindRequest>('/api/bind', async (req, res) => {
const bindRequest = req.body;
const bindingResult = await platform.zigBeeClient.bind(bindRequest.from, bindRequest.to, bindRequest.clusters, bindRequest.sourceEndpoint, bindRequest.targetEndpoint);
res.status(constants.HTTP_STATUS_OK);
res.contentType('application/json');
const result: BindUnbindResponse = {
data: {
from: bindRequest.from,
to: bindRequest.to,
clusters: bindingResult.successfulClusters,
failed: bindingResult.failedClusters
},
status: 'ok'
}
res.end(JSON.stringify(result));
});
express.post<string, any, BindUnbindResponse, BindUnbindRequest>('/api/unbind', async (req, res) => {
const bindRequest = req.body;
const bindingResult = await platform.zigBeeClient.unbind(bindRequest.from, bindRequest.to, bindRequest.clusters, bindRequest.sourceEndpoint, bindRequest.targetEndpoint);
res.status(constants.HTTP_STATUS_OK);
res.contentType('application/json');
const result: BindUnbindResponse = {
data: {
from: bindRequest.from,
to: bindRequest.to,
clusters: bindingResult.successfulClusters,
failed: bindingResult.failedClusters
},
status: 'ok'
}
res.end(JSON.stringify(result));
});
}
Example #10
Source File: api.ts From nouns-monorepo with GNU General Public License v3.0 | 6 votes |
createAPI = (): Express => {
const app = express();
app.use(express.json());
app.get('/', (_req, res) => {
res.status(200).send({
message: 'Nouns API Root',
});
});
app.get(
'/metadata/:tokenId',
param('tokenId').isInt({ min: 0, max: 1000 }),
async (req: Request, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).send({ errors: errors.array() });
}
const metadata = await getTokenMetadata(req.params.tokenId);
if (!metadata) {
return res.status(500).send({ error: 'Failed to fetch token metadata' });
}
res.send(metadata);
},
);
return app;
}
Example #11
Source File: routes.ts From advanced-node with GNU General Public License v3.0 | 6 votes |
setupRoutes = (app: Express): void => {
const router = Router()
readdirSync(join(__dirname, '../routes'))
.filter(file => !file.endsWith('.map'))
.map(async file => {
(await import(`../routes/${file}`)).default(router)
})
app.use('/api', router)
}
Example #12
Source File: app.ts From clean-ts-api with GNU General Public License v3.0 | 6 votes |
setupApp = async (): Promise<Express> => {
const app = express()
setupStaticFiles(app)
setupSwagger(app)
setupMiddlewares(app)
setupRoutes(app)
const server = setupApolloServer()
await server.start()
server.applyMiddleware({ app })
return app
}
Example #13
Source File: index.ts From react-typescript-boilerplate with MIT License | 6 votes |
/**
* 配置中间件
*/
export default function setupMiddlewares(server: Express, compiler: Compiler): void {
// 设置代理
proxyMiddleware(server);
// 使用 browserRouter 时,需要重定向所有 html 页面到首页
server.use(historyFallback());
// 开发 chrome 扩展的时候可能需要开启跨域,参考:https://juejin.im/post/5e2027096fb9a02fe971f6b8
server.use(cors());
// webpack 相关中间件
server.use(webpackMiddleware(compiler));
}
Example #14
Source File: server.ts From telefunc with MIT License | 6 votes |
async function installFrontend(app: Express) {
if (process.env.NODE_ENV === 'production') {
const root = __dirname
app.use(express.static(`${root}/dist/client`))
} else {
const vite = await import('vite')
const viteDevServer = await vite.createServer({
server: { middlewareMode: 'html' }
})
app.use(viteDevServer.middlewares)
}
}
Example #15
Source File: index.ts From discord-bot with MIT License | 6 votes |
export function init(): Express {
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.get('/', (req, res) => {
res.json(true);
});
app.post('/event', (req, res) => {
const token = req.body['api_token'];
if (!token || token !== process.env.DISCORD_BOT_API_TOKEN) {
return res.status(401).json('Wrong API Token.');
}
console.log('Event received: ', req.body);
onEventReceived(req.body);
return res.json('Event received.');
});
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
return app;
}
Example #16
Source File: index.ts From wise-old-man with MIT License | 6 votes |
setupServices() {
jobs.init();
hooks.setup();
Sentry.init({
dsn: env.SENTRY_DSN,
tracesSampleRate: 0.01,
integrations: [
new Sentry.Integrations.Http({ tracing: true }),
new Tracing.Integrations.Express({ app: this.express })
]
});
}
Example #17
Source File: index.ts From ExpressLRS-Configurator with GNU General Public License v3.0 | 5 votes |
app: Express | undefined;
Example #18
Source File: index.ts From davinci with MIT License | 5 votes |
expressApp: Express = express()
Example #19
Source File: api.ts From Discord-Bot-TypeScript-Template with MIT License | 5 votes |
private app: Express;
Example #20
Source File: index.ts From Adachi-BOT with MIT License | 5 votes |
private readonly app: Express;
Example #21
Source File: auth.ts From OpenVolunteerPlatform with MIT License | 5 votes |
export function buildKeycloakApolloConfig(app: Express, apolloConfig: any) {
const graphqlPath = `/graphql`;
console.log("Using keycloak configuration")
const memoryStore = new session.MemoryStore()
app.use(session({
secret: process.env.SESSION_SECRET_STRING || 'this should be a long secret',
resave: false,
saveUninitialized: true,
store: memoryStore
}))
const keycloak = new Keycloak({
store: memoryStore
}, config.keycloakConfig);
const keycloakSubscriptionHandler = new KeycloakSubscriptionHandler({ keycloak })
app.use(keycloak.middleware())
// For production we want to protect /graphql endpoint
// For development we want to test our queries using graphql playground
if(process.env.NODE_ENV === 'production'){
app.use(graphqlPath, keycloak.protect());
}
return {
typeDefs: [KeycloakTypeDefs, apolloConfig.typeDefs], // 1. Add the Keycloak Type Defs
schemaDirectives: KeycloakSchemaDirectives,
resolvers: apolloConfig.resolvers,
playground: apolloConfig.playground,
path: graphqlPath,
context: (context: any) => {
return {
...apolloConfig.context(context),
kauth: new KeycloakContext({ req: context.req }) // 3. add the KeycloakContext to `kauth`
}
},
subscriptions: {
onConnect: async (connectionParams, websocket, connectionContext) => {
const token = await keycloakSubscriptionHandler.onSubscriptionConnect(connectionParams)
if (!token) {
throw new Error("Cannot build keycloak token. Connection will be terminated")
}
return {
...apolloConfig.context,
kauth: new KeycloakSubscriptionContext(token)
}
}
},
}
}
Example #22
Source File: router.ts From snip with MIT License | 5 votes |
static registerRoutes(app: Express): void {
routes.forEach((route) => {
// Iterate and register each route
app.use(route.path, route.run());
});
}
Example #23
Source File: configure.ts From avalanche-faucet-legacy with BSD 3-Clause "New" or "Revised" License | 5 votes |
function beforeMiddleware(app: Express){
app.use(cors());
app.use(bodyParser.json());
app.enable('trust proxy');
app.use('/api', api)
}
Example #24
Source File: setupErrorHandlers.ts From commonwealth with GNU General Public License v3.0 | 5 votes |
setupErrorHandlers = (app: Express, rollbar: Rollbar) => {
// Rollbar notifications
app.use(rollbar.errorHandler());
// Handle 404 errors
app.use((req: Request, res: Response, next) => {
res.status(404);
res.json({
status: 404,
error: 'The server can not find the requested resource.',
});
});
// Handle our ServerErrors (500), AppErrors (400), or unknown errors.
app.use((error, req, res: Response, next) => {
if (error instanceof ServerError) {
console.trace(error);
rollbar.error(error); // expected server error
res.status(error.status).send({
status: error.status,
// Use external facing error message
error: 'Server error, please try again later.',
});
} else if (error instanceof AppError) {
rollbar.log(error); // expected application/user error
res.status(error.status).send({
status: error.status,
error: error.message,
});
} else {
console.trace(error);
rollbar.critical(error); // unexpected error
res.status(500);
res.json({
status: error.status,
error:
error.message ||
'Server error, unknown error thrown. Please try again later.',
});
}
});
}
Example #25
Source File: index.ts From fullstack-starterkit with MIT License | 5 votes |
app: Express = express()
Example #26
Source File: coordinator.ts From homebridge-zigbee-nt with Apache License 2.0 | 5 votes |
export function mapCoordinatorRoutes(express: Express, platform: ZigbeeNTHomebridgePlatform) {
express.get('/api/coordinator', async (_req, res) => {
const version = await platform.zigBeeClient.getCoordinatorVersion();
const permitJoin = await platform.zigBeeClient.getPermitJoin();
const normalizedCoordinator = normalizeDeviceModel(platform.zigBeeClient.getCoordinator(), platform.config.customDeviceSettings);
const coordinator: CoordinatorModel = {
...version,
...normalizedCoordinator,
permitJoin,
settings: {
ieeeAddr: normalizedCoordinator.ieeeAddr,
friendlyName: 'Coordinator'
}
};
res.status(constants.HTTP_STATUS_OK);
res.contentType('application/json');
res.end(JSON.stringify({ coordinator }));
});
express.get('/api/coordinator/permitJoin', async (_req, res) => {
res.status(constants.HTTP_STATUS_OK);
res.contentType('application/json');
res.end(JSON.stringify({ permitJoin: await platform.zigBeeClient.getPermitJoin() }));
});
express.post('/api/coordinator/permitJoin', async (_req, res) => {
await platform.zigBeeClient.permitJoin(true);
res.status(constants.HTTP_STATUS_OK);
res.contentType('application/json');
res.end(JSON.stringify({ permitJoin: true }));
});
express.delete('/api/coordinator/permitJoin', async (_req, res) => {
await platform.zigBeeClient.permitJoin(false);
res.status(constants.HTTP_STATUS_OK);
res.contentType('application/json');
res.end(JSON.stringify({ permitJoin: false }));
});
express.post('/api/coordinator/touchLink', async (_req, res) => {
const result = await platform.zigBeeClient.touchlinkFactoryReset();
res.status(constants.HTTP_STATUS_OK);
res.contentType('application/json');
res.end(JSON.stringify({ touchLink: result }));
});
}
Example #27
Source File: app.ts From msclub-backend with GNU General Public License v3.0 | 5 votes |
app: Express = express()
Example #28
Source File: auth.ts From office-booker with MIT License | 5 votes |
configureAuth = (config: Config, app: Express): Express => {
return app.use(async (req, res, next) => {
try {
if (config.authConfig.type === 'test') {
const response = config.authConfig.validate(req);
const userEmail = response?.email;
if (typeof userEmail !== 'string') {
throw new Unauthorized('Email property missing on auth validate response');
}
res.locals.user =
config.caseSensitiveEmail === true ? userEmail : userEmail.toLocaleLowerCase();
next();
} else {
//I'm passing in the access token in header under key accessToken
const authHeader = req.headers.authorization;
//Fail if token not present in header.
if (typeof authHeader !== 'string') throw new Unauthorized('Header not set');
const bearerRegex = /^Bearer ([a-zA-Z0-9_\-\.]*)$/g;
const parsed = bearerRegex.exec(authHeader);
const token = parsed?.[1];
if (typeof token !== 'string') throw new Unauthorized('Could not parse Bearer token');
const authResult = await validate(
{
region: config.authConfig.region,
userPoolId: config.authConfig.cognitoUserPoolId,
tokenUse: 'id',
},
token
);
if (authResult.valid) {
const userEmail = authResult.token.email as string;
res.locals.user =
config.caseSensitiveEmail === true ? userEmail : userEmail.toLocaleLowerCase();
next();
} else {
throw new Unauthorized('Bearer token not valid');
}
}
} catch (e) {
next(e);
}
return undefined;
});
}
Example #29
Source File: index.ts From payload with MIT License | 5 votes |
express: Express