.bin/snippets
#!/usr/bin/env node
const
fs = require( 'fs' ),
path = require( 'path' ),
OpenAPISnippet = require( 'openapi-snippet' ),
HTTPSnippet = require('httpsnippet'),
openAPI = require( '../web_deploy/openapi.json' ),
targets = [ 'shell_curl', 'node_llms' ];
// Add a target for the llms-api-node lib.
HTTPSnippet.addTargetClient( 'node', require( './httpsnippet-client-for-llms-node-api' ) );
function getFilepath( obj, target ) {
const
resource = obj.url.replace( 'https://example.tld/wp-json/llms/v1/', '' ).split( '/' ).join( '@' );
switch ( target ) {
case 'shell_curl':
lang = 'cURL';
ext = 'sh';
break;
case 'node_llms':
lang = 'Node.js';
ext = 'js';
break;
}
return `spec/code_samples/${ lang }/${ resource }/${ obj.method.toLowerCase() }.${ ext }`;
}
function getSnippet( obj, target ) {
return modSnippet( obj.snippets.filter( snip => snip.id === target )[0].content, target );
}
function modSnippet( snip, target ) {
if ( 'shell_curl' === target ) {
snip = snip.replace( "--header 'authorization: Basic REPLACE_BASIC_AUTH'", '--user ck_XXXXXX:cs_XXXXXX' );
}
return snip;
}
function writeSnippetForTarget( obj, target ) {
const filePath = getFilepath( obj, target );
fs.mkdirSync( path.dirname( filePath ), { recursive: true } );
fs.writeFileSync( filePath, getSnippet( obj, target ) );
}
try {
const results = OpenAPISnippet.getSnippets( openAPI, targets );
results.forEach( snip => {
if ( 'PARAMETERS' === snip.method ) {
return;
}
writeSnippetForTarget( snip, 'shell_curl' );
writeSnippetForTarget( snip, 'node_llms' );
} );
} catch ( err ) {
console.error( err );
}