|
| 1 | +const { existsSync } = require('fs'); |
| 2 | +const path = require('path'); |
| 3 | + |
| 4 | +const X_CODE_SAMPLES_PROPERTY = 'x-codeSamples'; |
| 5 | + |
| 6 | +const LANGUAGES = [ |
| 7 | + { lang: 'JavaScript', label: 'JS client' }, |
| 8 | +]; |
| 9 | + |
| 10 | +/** |
| 11 | + * This decorator adds the x-codeSamples property to the schema object if a file with the operationId exists in the |
| 12 | + * code samples directory. |
| 13 | + * This helps us add the samples in a consistent way and find out which operations are missing a sample. |
| 14 | + * |
| 15 | + * The added sample link will look like this: |
| 16 | + * x-codeSamples: |
| 17 | + * - lang: JavaScript |
| 18 | + * label: JS client |
| 19 | + * source: |
| 20 | + * $ref: ../../code_samples/js/acts_post.js |
| 21 | + */ |
| 22 | +function CodeSamplesDecorator(target) { |
| 23 | + if (!target.operationId) return; |
| 24 | + |
| 25 | + const codeSamples = []; |
| 26 | + |
| 27 | + for (const { lang, label } of LANGUAGES) { |
| 28 | + const codeSamplePath = path.join(__dirname, `../../openapi/code_samples/${lang.toLowerCase()}/${target.operationId}.js`); |
| 29 | + |
| 30 | + if (!existsSync(codeSamplePath)) { |
| 31 | + // Just use this console log in development to see which operations are missing a code sample. |
| 32 | + // console.log(`Missing code sample for operation ${target.operationId}`); |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + codeSamples.push({ |
| 37 | + lang, |
| 38 | + label, |
| 39 | + source: { |
| 40 | + $ref: codeSamplePath, |
| 41 | + }, |
| 42 | + }); |
| 43 | + } |
| 44 | + |
| 45 | + if (codeSamples.length) { |
| 46 | + target[X_CODE_SAMPLES_PROPERTY] = codeSamples; |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +module.exports = () => ({ |
| 51 | + // Redocly is using a visitor pattern. What the following code does is that whenever the traverser leaves a node of |
| 52 | + // type Tag or Operation, it executes CodeSamplesDecorator on it. |
| 53 | + Tag: { |
| 54 | + leave: CodeSamplesDecorator, |
| 55 | + }, |
| 56 | + Operation: { |
| 57 | + leave: CodeSamplesDecorator, |
| 58 | + }, |
| 59 | +}); |
0 commit comments