Open gresnick opened 2 weeks ago
There is an inject
option for prefixing arbitrary text.
However, in our case we use the same tooling to generate types from different OpenAPI schemas, and don't know beforehand whether a given format is actually used in a schema, so a static inject
isn't sufficient.
Instead, we track the usage out-of-band, and interpolate the openapi-typescript generated typesOutput
string into the final output
, and import the dependencies only when necessary.
// Track whether the import is necessary
let hasObjectId = false;
const typesOutput = await openapiTS(localPath, {
// ...other options
transform: (schema) => {
if ('format' in schemaObject && schemaObject.format === 'mongo-objectid') {
// This side-effect signals that the import is necessary
hasObjectId = true;
return ts.factory.createTypeReferenceNode('ObjectId');
}
}
});
const output = `${
// include imports if necessary
hasObjectId ?
"import { ObjectId } from 'mongodb';\n\n" :
''
}${
// stringify the openapi-typescript nodes
astToString(typesOutput)
}`;
fs.writeFileSync("interfaces.d.ts", output);
Description
This is more a basic question than a bug.
I am following the Node.js API docs with the example of replacing
Date
andDateTime
. I would like to use a custom library (e.g.luxon
) to provide these types.My script
The resulting
interfaces.d.ts
file has the types mapped correctlyhowever
DateTime
is unresolved.How do I inject
import { DateTime } from 'luxon';
intointerfaces.d.ts
?