express#Router TypeScript Examples
The following examples show how to use
express#Router.
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: restHandler.ts From AIPerf with MIT License | 6 votes |
// TODO add validators for request params, query, body
private checkStatus(router: Router): void {
router.get('/check-status', (req: Request, res: Response) => {
const ds: DataStore = component.get<DataStore>(DataStore);
ds.init().then(() => {
res.send(this.nniManager.getStatus());
}).catch(async (err: Error) => {
this.handleError(err, res);
this.log.error(err.message);
this.log.error(`Datastore initialize failed, stopping rest server...`);
await this.restServer.stop();
});
});
}
Example #2
Source File: v1.ts From dicio-api with MIT License | 6 votes |
export default function v1Routes(router: Router) {
router.get('/:word', meanings);
router.get('/allMeanings/:word', allMeanings);
router.get('/meanings/:word', meanings);
router.get('/synonyms/:word', synonyms);
router.get('/syllables/:word', syllables);
router.get('/sentences/:word', sentences);
return router;
}
Example #3
Source File: Root.ts From snip with MIT License | 6 votes |
// eslint-disable-next-line class-methods-use-this
run(): Router {
const router = Router();
// eslint-disable-next-line consistent-return
router.get('/*', async (req, res) => {
if (!req.url.slice(1)) return res.boom.notFound();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const url: any = await Snip.findOne({
id: req.url.slice(1), // gets FOO from snip.ml/FOO
});
if (url) {
res.redirect(301, url.url);
} else {
res.redirect(301, 'https://snip.ml');
}
});
return router;
}
Example #4
Source File: index.spec.ts From openapi-mock-express-middleware with MIT License | 6 votes |
describe('createMockMiddleware', () => {
it('should return an instance of the express router', async () => {
const middleware = createMockMiddleware({
spec: path.resolve(__dirname, '../test/fixtures/petstore.yaml'),
});
expect(Object.getPrototypeOf(middleware)).toBe(Router);
});
it('should throw an error if the given file does not exist', () => {
try {
createMockMiddleware({
spec: path.resolve(__dirname, '../test/fixtures/petstore_not_exist.yaml'),
});
throw new Error('exit');
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect(error).toHaveProperty(
'message',
`OpenAPI spec not found at location: ${path.resolve(
__dirname,
'../test/fixtures/petstore_not_exist.yaml'
)}`
);
}
});
});
Example #5
Source File: bundle.controller.ts From server-api with Apache License 2.0 | 6 votes |
public async boot(): Promise<Router> {
const router = Router();
router.post(
this.basepath,
await validationMiddleware({
path: this.basepath,
method: 'post',
documents: ['asyncapis', 'base'],
}),
this.bundle.bind(this)
);
return router;
}
Example #6
Source File: dataMiddleware.ts From TXQ with MIT License | 6 votes |
resFormat = (router: Router) => {
router.use((req: Request, res: Response, next: NextFunction) => {
res.api = {
status: 200,
errors: [],
result: [] || {},
};
next();
});
}
Example #7
Source File: app.ts From backstage with Apache License 2.0 | 6 votes |
export default async function createPlugin(
env: PluginEnvironment,
): Promise<Router> {
return await createRouter({
logger: env.logger,
config: env.config,
database: env.database,
appPackageName: 'example-app',
});
}
Example #8
Source File: index.ts From one-platform with MIT License | 5 votes |
router = Router()
Example #9
Source File: restHandler.ts From AIPerf with MIT License | 5 votes |
public createRestHandler(): Router {
const router: Router = Router();
router.use((req: Request, res: Response, next) => {
this.log.debug(`${req.method}: ${req.url}: body:\n${JSON.stringify(req.body, undefined, 4)}`);
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
res.setHeader('Content-Type', 'application/json');
next();
});
this.version(router);
this.checkStatus(router);
this.getExperimentProfile(router);
this.updateExperimentProfile(router);
this.importData(router);
this.startExperiment(router);
this.getTrialJobStatistics(router);
this.setClusterMetaData(router);
this.listTrialJobs(router);
this.getTrialJob(router);
this.addTrialJob(router);
this.cancelTrialJob(router);
this.getMetricData(router);
this.getMetricDataByRange(router);
this.getLatestMetricData(router);
this.exportData(router);
// Express-joi-validator configuration
router.use((err: any, req: Request, res: Response, next: any) => {
if (err.isBoom) {
this.log.error(err.output.payload);
return res.status(err.output.statusCode).json(err.output.payload);
}
});
return router;
}
Example #10
Source File: routes.ts From NLW-3.0 with MIT License | 5 votes |
routes = Router()
Example #11
Source File: appointments.routes.ts From gobarber-api with MIT License | 5 votes |
appointmentsRouter = Router()
Example #12
Source File: routes.ts From happy with MIT License | 5 votes |
routes = Router()
Example #13
Source File: index.ts From rocketseat-gostack-11-desafios with MIT License | 5 votes |
routes = Router()
Example #14
Source File: categories.routes.ts From TypeScript-in-Nodejs-Starter with MIT License | 5 votes |
categoriesRouter = Router()
Example #15
Source File: index.tsx From big-web-quiz with Apache License 2.0 | 5 votes |
router: Router = Router({
strict: true,
})
Example #16
Source File: createRouter.ts From davinci with MIT License | 5 votes |
function createRouterAndSwaggerDoc(...options): Router | DaVinciExpress {
const {
Controller,
resourceName: rsName,
contextFactory,
router = express.Router(),
ajvFactory
} = processParameters(options as [CreateRouterParameters] | CreateRouterParametersArray);
validateController(Controller);
// get a resource name either supplied or derive from Controller name
const resourceName = rsName || Controller.name.replace(/Controller$/, '').toLowerCase();
// get controller metadata
const metadata: IControllerDecoratorArgs =
Reflector.getMetadata('davinci:openapi:controller', Controller)?.reduce(
(acc, controllerMeta) => Object.assign(acc, controllerMeta),
{}
) ?? {};
const basepath = metadata.basepath || '/';
const { resourceSchema } = metadata;
const { additionalSchemas } = metadata;
// create the controller from the supplied class
const controller = new Controller();
// create the swagger structure
const mainDefinition = resourceSchema ? createOpenapiSchemaDefinitions(resourceSchema) : {};
const additionalDefinitions = _.reduce(
additionalSchemas,
(acc, schema) => ({ ...acc, ...createOpenapiSchemaDefinitions(schema) }),
[]
);
const { paths, definitions: pathDefinitions, validationOptions } = createPaths(Controller);
const definition = {
definitions: {
...mainDefinition,
...additionalDefinitions,
...pathDefinitions
},
paths
};
// now process the swagger structure and get an array of method/path mappings to handlers
const routes = createRouteHandlers(controller, definition, validationOptions, contextFactory, ajvFactory);
// add them to the router
routes.forEach(route => {
const routePath = urlJoin(basepath, route.path);
return router[route.method](routePath, ...route.handlers);
});
openapiDocs.addResource(definition, resourceName, basepath);
return router;
}
Example #17
Source File: oauth.ts From jmix-frontend with Apache License 2.0 | 5 votes |
createOauthRouter = (allowInvalidCreds) => {
const oauthRouter = Router()
oauthRouter.post('/oauth/token', (req, res) => {
const {username, password} = getCreds(req);
let accessToken;
let refreshToken;
let sessionId;
if (username === 'admin' && password === 'admin') {
accessToken = '-xMM4dlsCNjGtYviFArebBXep7w'
refreshToken = 'yi2VX-JIHdd04EKlysV4SoxSVDA'
sessionId = '9563D73FA2ADCD6774BAAA06984EE2E7'
}
if (username === 'user1' && password === 'user1') {
accessToken = 'XONNmH89K2JKGu-To-oPNj1mk9o'
refreshToken = 'HP8abXBteTinzbZkXSW3OoKrCuQ'
sessionId = 'CD85C80F32231478C77D9355DC8769F8'
}
if (username === 'user2' && password === 'user2') {
accessToken = 'EY5etaIDPNMj3WF4T4CdTlCPm34'
refreshToken = '6sEqd3xnTt3AnlaRbg4dUF21WZA'
sessionId = 'F4615CFFBAD97FB28431AE644EEEDD8D'
}
if (accessToken == null) {
if (allowInvalidCreds === false) {
return res.status(400).send({
"error": "invalid_grant",
"error_description": "Bad credentials"
})
}
accessToken = '02DU0_xOWE1Hn-pmIGuc6tFBilU';
refreshToken = 'N6LgoQgbIklnDhz3VgbaxHJ6oKQ';
sessionId = 'F55D157FF35E6BBB6B69F7F3DD56B746';
}
res.send({
"access_token": `${accessToken}`,
"token_type": "bearer",
"refresh_token": `${refreshToken}`,
"expires_in": 43199,
"scope": "api",
"OAuth2.SESSION_ID": `${sessionId}`
}
)
})
oauthRouter.post('/oauth/revoke', (req, res) => {
res.status(200).end()
})
return oauthRouter;
}
Example #18
Source File: guilds-controller.ts From Discord-Bot-TypeScript-Template with MIT License | 5 votes |
public router: Router = router();
Example #19
Source File: appointments.routes.ts From hotseat-api with MIT License | 5 votes |
appointmentsRouter = Router()
Example #20
Source File: api.ts From master-frontend-lemoncode with MIT License | 5 votes |
api = Router()