metadevpro / openapi3-ts Goto Github PK
View Code? Open in Web Editor NEWTS Model & utils for creating and exposing OpenAPI 3.x contracts.
License: MIT License
TS Model & utils for creating and exposing OpenAPI 3.x contracts.
License: MIT License
can add a param to the builder constructor?
export class OpenApiBuilder {
rootDoc: oa.OpenAPIObject;
static create(doc?: oa.OpenAPIObject): OpenApiBuilder {
return new OpenApiBuilder();
}
constructor(doc?: oa.OpenAPIObject) {
this.rootDoc = doc || {
......
I'm a bit confused.
If possible, could you please clarify how to operate OAS 3.0, if the module exports DSL and the model of 3.1 only?
Should Iimport from "openapi3-ts/dist/cjs/model/openapi30"
directly or what exactly is supposed?
Maybe it should be explained in the changelog or Readme.
Line 1 in 26e1740
openapi3-ts/src/model/index.ts
Line 1 in 26e1740
Line 7 in 26e1740
Hello.
Can I use it for generate API layer for Angular from remote openapi.json? Could you add usage examples?
Very Poor documentation!
No example of how to use it.
@pjmolina please at least attach an example.
After searching a lot I got this code sandbox example.
10.11.0
to 10.11.1
.This version is covered by your current version range and after updating it in your project the build failed.
@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Cool looking project, but not entirely sure of all the use cases.
Currently implementing contract testing using Open API v3 with Express and writing all our own utils. We'd love to use Typescript as it makes a lot of sense for contract testing.
Note: Have read 2 questions on usage and still not clear, hence this question. Request some help on usecases.
our application is based on Typescript, the API is hand-written in swagger hub. Looking for tools/api that would ensure the contract and implementation are aligned. Wanted to know, how this project can help in that regard. I tried a sample
import {SchemaObject} from "openapi3-ts";
export class TestSchema implements SchemaObject {
title = "test ";
type = "object";
properties = {
"test": {
type: "string"
}
};
}
Questions:
As you know, the JSON schema for OpenAPI versions 3.0.x and 3.1.x differ. Currently, this package uses the same model for both versions. Thus, it cannot guarantee that the produced openapi.json will comply either version. In particular, it's not possible to specify the targeted OpenAPI version which is desirable as tools, that have the openapi.json as input, might only support certain versions of OpenAPI.
This is a valid json schema which breaks with the implementation used in this library
oneOf: [
{
type: 'object',
required: ['status'],
properties: {
status: { type: 'string', pattern: JobApplicant.Status.NEW },
payload: {
type: 'string'
},
}
}, {
type: 'object',
required: ['status'],
properties: {
status: { type: 'string', pattern: 'contact' },
}
}
]
Breaks with error
Type '{ status: { type: string; pattern: string; }; payload?: undefined; }' is not assignable to type '{ [propertyName: string]: ReferenceObject | SchemaObject; }'.
as the second option hasn't such type payload
As OpenApi use the JSON Schema Specification, exclusiveMinimum/exclusiveMaximum should be numbers and not booleans.
First thank you so much for this library - it's been a big time saver! 😄
I think I've found the following bugs:
interface OpenAPIObject {
...
security: SecurityRequirementObject // should be SecurityRequirementObject[]
}
interface OperationObject {
...
security: SecurityRequirementObject // same thing here: SecurityRequirementObject[]
}
Refs:
Hello. I wanted to try the latest major update, but I'm getting the following error:
node_modules/openapi3-ts/dist/cjs/index.js:3
__exportStar(require("./model/index.js"), exports);
^
ReferenceError: __exportStar is not defined
Node version is 18.6.
Typescript 4.7.4
Do you know why this is happening and/or how it can be fixed?
/**
* Type gate to ensure an object has been de-referenced.
*
* @param obj The object to check.
*/
function isDereferencedObject<T extends object | ReferenceObject>(
obj: T
): obj is Exclude<T, ReferenceObject> {
return !isReferenceObject(obj);
}
Hello there,
First thanks for the heavy lifting done in this library, it's a pleasure to not have to implement the OAI spec in typescript :)
A quick question regarding the OpenAPIObject
's paths
property.
I'm trying to get a get
OperationObject
from the main OpenAPI object, so I would say I should do something like openapi.paths['/my/path'].get
, which doesn't compile. So I went looking at the definition, and found:
interface OpenAPIObject extends ISpecificationExtension {
paths: {[path: string]: PathObject };
}
export interface PathObject extends ISpecificationExtension {
[path: string]: PathItemObject | any;
}
export interface PathItemObject extends ISpecificationExtension {
get?: OperationObject;
}
Why is there two indexed object ? The specification tells us that the first {[path: string]: PathObject }
should be a PathsObject
but maybe there is reason for the other indirection ?
Thanks,
François
After upgrading from version 4.3.1 to version 4.3.2, imports like:
import { ServerObject } from 'openapi3-ts/oas31'
fail with the following error
Cannot find module 'openapi3-ts/oas31' or its corresponding type declarations.
There are types at '/path/to/my/project/node_modules/openapi3-ts/dist/oas31.d.ts', but this result could not be resolved under your current 'moduleResolution' setting.
Consider updating to 'node16', 'nodenext' or 'bundler'.
Setting the 'moduleResolution' setting from node
to node16
, nodenext
or bundler
is not an option because it causes errors with other packages.
Node version: 20.14.0
Using the recent version (4.2.0) I'm getting OpenAPI 3.1 validation error regarding SchemaObject's examples
being object instead of array.
It's caused by the changes in this PR: #124
In that PR examples
were changed from any[]
to ExamplesObject
.
The specification refers to this document:
https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#page-22
which as well as the validator says that examples
must be array.
I'm trying to find the source of truth and/or where the mistake is.
@kkolstad || @pjmolina ,
could you tell me please which information the changes from #124 are based on?
Is there any other RFC or revision that changed the examples
from array to object?
Is that an issue of the validator or of the PR?
Hi! Nice project.
I was wondering if you could just publish the OpenAPI types so others can import and re-use them? That would be really useful for other TS-based projects.
Thanks.
Looking into the spec, components should not be required, yet there are.
Same applies for components properties.
4.2.3
to 4.2.4
.This version is covered by your current version range and after updating it in your project the build failed.
@types/chai is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
The output OpenAPI spec does not place the description of a (query string) parameter in the right place, and thus is lost when rendered.
Example:
const getServiceAreasRequestSchema = z
.object({
clientBC: z.string().describe("Business code identifying the Client"),
});
// ... elsewhere ....
import { OpenApiGeneratorV3, OpenAPIRegistry } from "@asteasolutions/zod-to-openapi";
import { OpenAPIObject } from "openapi3-ts/oas30";
// ...
registry.registerPath({
path: "/clients/getServiceAreas",
method: "get",
request: { query: getServiceAreasRequestSchema },
responses: {
"200": { content: { "application/json": { schema: serviceAreaSchema.array() } } },
},
});
Results in OpenAPI spec:
/clients/getServiceAreas:
get:
parameters:
- schema:
type: string
minLength: 1
description: Business code identifying the Client
required: true
name: clientBC
in: query
responses:
"200":
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/ServiceArea"
The description: Business code identifying the Client
belongs one element up, next to the parameter name
and required
. See https://swagger.io/docs/specification/describing-parameters/
As a result, the description is not rendered by Swagger UI.
Hi!
When I open a project that uses this package, VSCode reports errors like the following:
Cannot write file 'node_modules/openapi3-ts/dist/dsl/openapi-builder30.d.ts' because it would overwrite input file.
The published package contains a tsconfig.json
file with compileOnSave": true
in it: https://www.npmjs.com/package/openapi3-ts/v/4.3.1?activeTab=code
I think these source files should be omitted when the package is published to npm.
openapi3-ts/src/model/OpenApi.ts
Line 61 in d650cc9
heaer
should be header
I don't seem to see the relevant function in the dsl.
thank.
While trying to upgrade to [email protected]
in my project, I suddenly started getting this error on all my imports:
import { oas31 } from 'openapi3-ts';
^^^^^
SyntaxError: Named export 'oas31' not found. The requested module 'openapi3-ts' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'openapi3-ts';
const { oas31 } = pkg;
I'm guessing this is happening because my project is ESM. It used to work fine with [email protected]
.
I'm using TypeScript 5.0.4, and my tsconfig.json
looks like this:
{
"compilerOptions": {
"lib": ["ESNext", "dom"],
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"resolveJsonModule": true,
"outDir": "dist"
}
}
OAS 3.1 introduced the const
keyword (see discussion), syntactically equivalent to a single value enum, for example:
{
"components": {
"schemas": {
"BingData": {
"additionalProperties": false,
"properties": {
"bing": {
"const": "Anything You Need",
"title": "Bing"
}
},
"required": [
"bing"
],
"title": "BingData",
"type": "object"
},
"DingData": {
"additionalProperties": false,
"properties": {
"anything_you_need": {
"const": "Anything You Need",
"title": "Anything You Need"
}
},
"required": [
"anything_you_need"
],
"title": "DingData",
"type": "object"
}
},
"info": {
"title": "Events",
"version": "0.1.0"
},
"openapi": "3.1.0"
}
}
Supporting this in the library will be really useful for consumers to be able to account for this keyword when parsing schemas.
I'm not entirely sure how this would be typed as I can see that the enum keyword is currently typed as any[]
here
https://github.com/metadevpro/openapi3-ts/blob/master/src/model/OpenApi.ts#L58
export interface PathItemObject extends ISpecificationExtension {
$ref?: string;
summary?: string;
description?: string;
get?: OperationObject;
put?: OperationObject;
post?: OperationObject;
delete?: OperationObject;
options?: OperationObject;
head?: OperationObject;
patch?: OperationObject;
trace?: OperationObject;
servers?: ServerObject;
parameters?: {
[param: string]: ParameterObject;
};
}
Should be:
export interface PathItemObject extends ISpecificationExtension {
$ref?: string;
summary?: string;
description?: string;
get?: OperationObject;
put?: OperationObject;
post?: OperationObject;
delete?: OperationObject;
options?: OperationObject;
head?: OperationObject;
patch?: OperationObject;
trace?: OperationObject;
servers?: ServerObject;
parameters?: (ParameterObject | ReferenceObject)[];
}
As defined in the documentation.
The ParameterObject has it defined correctly.
12.7.0
to 12.7.1
.This version is covered by your current version range and after updating it in your project the build failed.
@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
Hey there - thanks for this library! It's super helpful.
One thing is a little bit troublesome, though. As of OpenAPI 3.1, OAS uses a complete superset of JSON Schema. To this end, juggling between the slightly different openapi3-ts
and @types/json-schema
types is a bit of a bear.
My use case, personally, is that I'm using the same schemas when I pass them to Fastify's ajv
validator as I do to openapi3-ts
. Maybe there's a way we (I'm happy to help if I can) can synchronize these together?
lib/TypeConverter.ts:44:36 - error TS2339: Property 'content' does not exist on type 'ReferenceObject | ResponseObject'.
Property 'content' does not exist on type 'ReferenceObject'.
44 content = response.content;
~~~~~~~
node_modules/openapi3-ts/src/model/OpenApi.ts:84:9 - error TS2322: Type 'undefined' is not assignable to type 'PathItemObject'.
84 return undefined;
~~~~~~~~~~~~~~~~~
{
"openapi3-ts": "^1.1.0",
"typescript": "^3.2.2",
}
➜ node -v
v10.15.0
Are PathItemObject
and ReferenceObject
not correctly defined?
package.json
{
"type": "module",
"devDependencies": {
"openapi3-ts": "^4.1.1"
}
}
app.mjs
import x from 'openapi3-ts/oas31';
const builder = new x.OpenApiBuilder();
console.log(builder.rootDoc);
it fails to import when running node app.mjs
(node:59840) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
.pnpm/[email protected]/node_modules/openapi3-ts/dist/mjs/oas31.js:1
export * from './dsl/openapi-builder31';
^^^^^^
SyntaxError: Unexpected token 'export'
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1195:20)
at Module._compile (node:internal/modules/cjs/loader:1239:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
at Module.load (node:internal/modules/cjs/loader:1133:32)
at Module._load (node:internal/modules/cjs/loader:972:12)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:165:29)
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
Node.js v19.9.0
It's probably because the published package.json does not have "type": "module"
, or that the published files does not end with ".mjs"
If you are building an ESM module and you use the import format:
import { OpenAPIObject } from "openapi3-ts/src/model/openapi31";
and use mocha with:
{
"loader": "ts-node/esm"
}
unit tests will fail.
The "fix" is to use the import format:
import { oas31 } from "openapi3-ts";
Since the second format works, I don't expect any code change here. I'm mainly creating this issue in case others run into the same problem.
It might be good to update the readme to note this.
I would like to propose bumping up the major version of this package from 0
to 1
, to signalize consumers we are ready for general use.
As semver says:
If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.
There are already more than 10 projectsdepending on openapi3-ts
and the stability of its API, see https://www.npmjs.com/browse/depended/openapi3-ts.
@pjmolina thoughts?
https://github.com/metadevpro/openapi3-ts/blob/master/src/dsl/OpenApiBuilder.spec.ts#L7
Although this passes, the OpenApi Object is missing the security
and externalDocs
properties.
Lines 306 and 308 have been changed in this commit:
e7a0851
These changes have been released in version 3.0.0.
However, according to this spec, exclusiveMaximum
must be boolean:
https://datatracker.ietf.org/doc/html/draft-wright-json-schema-validation-00#section-5.3
More than that, the Swagger validator complains about numeric value as well:
I think that the mentioned commit should be reverted.
Otherwise, could you please clarify what was the reason for that change?
We are trying to update to 4.0.2 and our builds are broken with the following errors after changing my imports as documented.
Changed import to:
import { MediaTypeObject } from 'openapi3-ts/src/model/openapi31';
I get:
node_modules/openapi3-ts/src/model/oas-common.ts:21:16 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ISpecificationExtension'.
No index signature with a parameter of type 'string' was found on type 'ISpecificationExtension'.
21 return obj[extensionName];
~~~~~~~~~~~~~~~~~~
node_modules/openapi3-ts/src/model/oas-common.ts:31:9 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ISpecificationExtension'.
No index signature with a parameter of type 'string' was found on type 'ISpecificationExtension'.
31 obj[extensionName] = extension;
~~~~~~~~~~~~~~~~~~
node_modules/openapi3-ts/src/model/specification-extension.ts:28:13 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SpecificationExtension'.
No index signature with a parameter of type 'string' was found on type 'SpecificationExtension'.
28 if (this[extensionName]) {
~~~~~~~~~~~~~~~~~~~
node_modules/openapi3-ts/src/model/specification-extension.ts:29:20 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SpecificationExtension'.
No index signature with a parameter of type 'string' was found on type 'SpecificationExtension'.
29 return this[extensionName];
~~~~~~~~~~~~~~~~~~~
node_modules/openapi3-ts/src/model/specification-extension.ts:39:9 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SpecificationExtension'.
No index signature with a parameter of type 'string' was found on type 'SpecificationExtension'.
39 this[extensionName] = payload;
~~~~~~~~~~~~~~~~~~~
As the spec the X-props are allowed to add customised info, I am wondering how that can be integrated with this lib?
10.12.11
to 10.12.12
.This version is covered by your current version range and after updating it in your project the build failed.
@types/node is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.
There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.
Your Greenkeeper Bot 🌴
The swagger-schema-official implementation for Swagger 2.0 described .properties thus:
properties?: {[propertyName: string]: Schema};
Also .allOf, .oneOf, and .anyOf are lists.
Therefore I would expect their types to be:
allOf?: (SchemaObject | ReferenceObject)[];
oneOf?: (SchemaObject | ReferenceObject)[];
anyOf?: (SchemaObject | ReferenceObject)[];
properties?: {[propertyName: string]: (SchemaObject | ReferenceObject)};
Am I missing something?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.