|
6 | 6 | 'use strict'
|
7 | 7 | const requestManager = require("../../core/request-manager");
|
8 | 8 | const API = require("../../../nr-security-api");
|
| 9 | +const routeManager = require('../../core/route-manager'); |
9 | 10 | const logger = API.getLogger();
|
| 11 | +const lodash = require('lodash'); |
| 12 | +const { ATTHERATE, DOUBLE_DOLLAR, EMPTY_STR } = require('../../core/constants'); |
10 | 13 |
|
11 | 14 | const semver = require('semver')
|
| 15 | +const fs = require('fs'); |
| 16 | +const path = require('path'); |
12 | 17 |
|
13 | 18 | module.exports = function initialize(shim, nextjs) {
|
14 | 19 | const nextVersion = shim.require('./package.json').version
|
15 | 20 | logger.info("Instrumenting nextjs", nextVersion);
|
16 | 21 |
|
17 | 22 | const nextServer = nextjs.default;
|
18 | 23 | hookRunAPI(shim, nextServer.prototype, nextVersion);
|
| 24 | + |
| 25 | + //TODO need to update for API endpoints |
| 26 | + try { |
| 27 | + const appRoot = process.env.PWD; |
| 28 | + const searchPath = appRoot + '/.next/server/pages/api'; |
| 29 | + const allAPIEndpoints = getAllAPIEndpoints(searchPath); |
| 30 | + logger.debug("allAPIEndpoints:", allAPIEndpoints); |
| 31 | + for (let index = 0; index < allAPIEndpoints.length; index++) { |
| 32 | + const element = allAPIEndpoints[index]; |
| 33 | + let key = "*" + ATTHERATE + element; |
| 34 | + routeManager.setRoute(key, EMPTY_STR); |
| 35 | + } |
| 36 | + } catch (error) { |
| 37 | + logger.debug("Error while getting all API end points for next.js", error); |
| 38 | + } |
| 39 | + |
| 40 | + |
19 | 41 | }
|
20 | 42 |
|
21 | 43 | /**
|
@@ -91,3 +113,33 @@ function extractParams(shim, page, params) {
|
91 | 113 | }
|
92 | 114 | }
|
93 | 115 |
|
| 116 | + |
| 117 | +/** |
| 118 | + * Utility to scan pages directory to get all avaible routes |
| 119 | + * @param {*} dir |
| 120 | + * @returns |
| 121 | + */ |
| 122 | +const getAllAPIEndpoints = (dir) => { |
| 123 | + logger.debug("dir is:", dir) |
| 124 | + const apiEndpoints = []; |
| 125 | + |
| 126 | + const scanDirectory = (currentDir) => { |
| 127 | + logger.debug("currentDir is:", currentDir) |
| 128 | + const files = fs.readdirSync(currentDir); |
| 129 | + |
| 130 | + files.forEach((file) => { |
| 131 | + const filePath = path.join(currentDir, file); |
| 132 | + const isDirectory = fs.statSync(filePath).isDirectory(); |
| 133 | + |
| 134 | + if (isDirectory) { |
| 135 | + scanDirectory(filePath); |
| 136 | + } else { |
| 137 | + const apiEndpoint = filePath.replace(`${dir}/`, '/api/').replace(/\.js*.*/, ''); |
| 138 | + apiEndpoints.push(apiEndpoint); |
| 139 | + } |
| 140 | + }); |
| 141 | + }; |
| 142 | + |
| 143 | + scanDirectory(dir); |
| 144 | + return apiEndpoints; |
| 145 | +}; |
0 commit comments