Exposing the hobnob.yaml file is as simple as adding a new endpoint to our API. However, the specification file is located at spec/openapi/hobnob.yaml, which is outside the dist/ directory of our application. Therefore, first, we should modify our serve script to also copy the OpenAPI specification to the root of the dist/ directory after the application has been built:
"dev:serve": "yarn run build && cp spec/openapi/hobnob.yaml dist/openapi.yaml && dotenv -e envs/.env node dist/index.js",
"serve": "yarn run build && cp spec/openapi/hobnob.yaml dist/openapi.yaml && dotenv -e envs/.env pm2 start dist/index.js",
Now, inside src/index.js, we need to add a new endpoint to retrieve and serve that same openapi.yaml. Add the following to src/index.js.
import fs from 'fs';
...
app.get('/openapi.yaml', (req, res, next) => {
fs.readFile(`${__dirname}/openapi.yaml`, (err, file) => {
if (err) {
res.status(500);
res.end();
return next();
}
res.write(file);
res.end();
return next();
});
});
Now, whilst running the dev:serve script, open your browser to http://127.0.0.1:8080/openapi.yaml. You should see the OpenAPI specification displayed on the screen!