Skip to content
This repository has been archived by the owner on Oct 5, 2023. It is now read-only.

feat: rewriting the library in typescript #210

Merged
merged 5 commits into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
coverage/
node_modules/
dist/
20 changes: 17 additions & 3 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
{
"extends": "@readme/eslint-config",
"extends": [
"@readme/eslint-config",
"@readme/eslint-config/docs",
"@readme/eslint-config/typescript"
],
"plugins": ["jsdoc"],
"root": true,
"rules": {
"consistent-return": "off",
"no-else-return": "off"
"@typescript-eslint/no-explicit-any": "off",

"camelcase": ["error", { "allow": ["OpenAPIV3_1"] }],

"jsdoc/require-jsdoc": "error",
"jsdoc/require-param": "off",
"jsdoc/require-param-type": "off",
"jsdoc/require-returns": "off",
"jsdoc/require-returns-type": "off",

"no-case-declarations": "off"
}
}
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,5 @@ jobs:
node-version: ${{ matrix.node-version }}

- run: npm ci
- run: npm run build
- run: npm test
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
coverage/
dist/
node_modules/
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ __tests__/
coverage/
.eslint*
.prettier*
jest.*.js
kanadgupta marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
coverage/
dist/
2 changes: 1 addition & 1 deletion LICENSE.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2019 ReadMe
Copyright (c) 2022 ReadMe

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
31 changes: 19 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,24 @@ npm install oas-normalize --save

# Usage

It's pretty simple:

```javascript
const OASNormalize = require('oas-normalize');
import OASNormalize from 'oas-normalize';
erunion marked this conversation as resolved.
Show resolved Hide resolved
// const { default: OASNormalize } = require('oas-normalize'); // If you're using CJS.

const oas = new OASNormalize(
// Or a string, pathname, JSON blob, whatever
'https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore-expanded.yaml'
);

oas.validate().then(definition => {
// Definition will always be JSON, and valid.
console.log(definition);
}).catch(err => {
console.log(err);
});
oas
.validate()
.then(definition => {
// Definition will always be JSON, and valid.
console.log(definition);
})
.catch(err => {
console.log(err);
});
```

# Errors
Expand Down Expand Up @@ -59,18 +61,23 @@ For validation errors, when available, you'll get back an object:

If you want some more functionality, you can do anything here:

<!--
Prettier's table formatting sucks, hence the ignore block below.
-->
<!-- prettier-ignore-start -->
| Function | What it does |
| :--- | :--- |
| `.load()` | Just load the file, valid or not, as JSON |
| `.bundle()` | Bring together all files into one JSON blob (but retain `$ref` pointers) |
| `.deref()` | Resolve `$ref` pointers |
| `.validate([convertToLatest?])` | Validate the whole thing! |
<!-- prettier-ignore-end -->

# Other Little Features

### Always Return OpenAPI 3.x

If you want `.validate` to always return an OpenAPI 3.x definition, supply `true` as its argument:
If you want `.validate()` to always return an OpenAPI 3.x definition, supply `true` as its argument:

```js
OASNormalize.validate(true).then(...);
Expand All @@ -81,7 +88,7 @@ OASNormalize.validate(true).then(...);
For security reasons, you need to opt into allowing fetching by a local path. To enable it supply the `enablePaths` option to the class instance:

```js
const oas = new OASNormalize('./petstore.json', { enablePaths: true })
const oas = new OASNormalize('./petstore.json', { enablePaths: true });
```

### Colorized errors
Expand All @@ -91,7 +98,7 @@ If you wish errors from `.validate()` to be styled and colorized, supply `colori
```js
const oas = new OASNormalize('https://example.com/petstore.json', {
colorizeErrors: true,
})
});
```

Error messages will look like such:
Expand Down
5 changes: 4 additions & 1 deletion __tests__/.eslintrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"extends": "@readme/eslint-config/testing"
"extends": "@readme/eslint-config/testing",
"rules": {
"jsdoc/require-jsdoc": "off"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12815,17 +12815,3 @@ Object {
],
}
`;

exports[`#validate should colorize errors when \`opts.colorizeErrors\` is present 1`] = `
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This got removed because we're skipping this test and Jest didn't carry it over when it moved the snapshot. If we ever re-enable this test this snapshot will come back then.

[SyntaxError: OpenAPI schema validation failed.

REQUIRED must have required property 'openIdConnectUrl'

  24 | "components": {
  25 | "securitySchemes": {
> 26 | "tlsAuth": {
  | ^ ☹️ openIdConnectUrl is missing here!
  27 | "type": "mutualTLS"
  28 | }
  29 | }]
`;
51 changes: 30 additions & 21 deletions __tests__/index.test.js → __tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
/* eslint-disable import/no-dynamic-require, global-require */
const fs = require('fs');
const path = require('path');
const nock = require('nock');
const OASNormalize = require('..');
import type { OpenAPIV3 } from 'openapi-types';

import fs from 'fs';
import path from 'path';

import nock from 'nock';

import OASNormalize from '../src';

function cloneObject(obj) {
return JSON.parse(JSON.stringify(obj));
Expand All @@ -23,7 +27,7 @@ describe('#load', () => {
});

it('should reject if unrecognized file supplied', async () => {
await expect(new OASNormalize().load()).rejects.toThrow('Could not load this file.');
await expect(new OASNormalize(cloneObject).load()).rejects.toThrow('Could not load this file.');
});

it('should support JSON objects', async () => {
Expand Down Expand Up @@ -82,34 +86,39 @@ describe('#load', () => {

describe('#bundle', () => {
it('should bundle an external schema in', async () => {
const petSchema = require('./__fixtures__/bundle/pet.json');
const petSchema = await import('./__fixtures__/bundle/pet.json').then(r => r.default);
const contents = require.resolve('./__fixtures__/bundle/definition.json');
const o = new OASNormalize(contents, { enablePaths: true });
const bundled = await o.bundle();
const bundled = (await o.bundle()) as OpenAPIV3.Document;

expect(bundled.components.requestBodies.Pet.content).toStrictEqual({
'application/json': {
schema: {
$ref: '#/components/requestBodies/Pet/content/application~1xml/schema',
expect(bundled.components?.requestBodies?.Pet).toStrictEqual({
description: 'Pet object that needs to be added to the store',
required: true,
content: {
'application/json': {
schema: {
$ref: '#/components/requestBodies/Pet/content/application~1xml/schema',
},
},
'application/xml': {
schema: petSchema,
},
},
'application/xml': {
schema: petSchema,
},
});
});
});

describe('#deref', () => {
it('should dereference a definition', async () => {
const openapi = require('@readme/oas-examples/3.0/json/petstore.json');
const openapi = await import('@readme/oas-examples/3.0/json/petstore.json').then(r => r.default);
expect(openapi.paths['/pet'].post.requestBody).toStrictEqual({
$ref: '#/components/requestBodies/Pet',
});

const o = new OASNormalize(cloneObject(openapi));
const deref = await o.deref();
expect(deref.paths['/pet'].post.requestBody).toStrictEqual({
const deref = (await o.deref()) as OpenAPIV3.Document;

expect(deref?.paths?.['/pet']?.post?.requestBody).toStrictEqual({
description: 'Pet object that needs to be added to the store',
required: true,
content: {
Expand All @@ -122,7 +131,7 @@ describe('#deref', () => {

describe('#validate', () => {
it("should not convert a Swagger definition to OpenAPI if we don't want to", async () => {
const swagger = require('@readme/oas-examples/2.0/json/petstore.json');
const swagger = await import('@readme/oas-examples/2.0/json/petstore.json').then(r => r.default);
const o = new OASNormalize(cloneObject(swagger));

await expect(o.validate()).resolves.toStrictEqual(swagger);
Expand Down Expand Up @@ -184,7 +193,7 @@ describe('#validate', () => {
['OpenAPI 3.1', '3.1'],
])('%s support', (_, version) => {
it('should validate a URL hosting JSON as expected', async () => {
const json = require(`@readme/oas-examples/${version}/json/petstore.json`);
const json = await import(`@readme/oas-examples/${version}/json/petstore.json`).then(r => r.default);
kanadgupta marked this conversation as resolved.
Show resolved Hide resolved

const mock = nock('http://example.com').get(`/api-${version}.json`).reply(200, cloneObject(json));
const o = new OASNormalize(`http://example.com/api-${version}.json`);
Expand Down Expand Up @@ -229,11 +238,11 @@ describe('#version', () => {

it('should detect an OpenAPI definition', async () => {
await expect(
new OASNormalize(require('@readme/oas-examples/3.0/json/petstore.json'), { enablePaths: true }).version()
new OASNormalize(require.resolve('@readme/oas-examples/3.0/json/petstore.json'), { enablePaths: true }).version()
).resolves.toBe('3.0.0');

await expect(
new OASNormalize(require('@readme/oas-examples/3.1/json/petstore.json'), { enablePaths: true }).version()
new OASNormalize(require.resolve('@readme/oas-examples/3.1/json/petstore.json'), { enablePaths: true }).version()
).resolves.toBe('3.1.0');
});
});
9 changes: 9 additions & 0 deletions __tests__/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"module": "es6",
"moduleResolution": "node",
"noImplicitAny": false,
"resolveJsonModule": true
}
}
120 changes: 0 additions & 120 deletions index.js

This file was deleted.

Loading