Spectral - Unable to lint oas warnings via JS API

Hi,

I am trying to replicate CLI lint errors/warning via JS API, but only seeing base “parser” warnings, the oas specific errors/warnings are not flagged in the api result, here is the code snippet -

constructor(ruleSets) {
this.ruleSets = ruleSets;
this.spectral = new Spectral();
this.spectral.registerFormat(‘oas2’, isOpenApiv2);
this.spectral.registerFormat(‘oas3’, isOpenApiv3);
this.spectral.loadRuleset(‘spectral:oas’);
}

async lint(raw) {
const body = raw.body || raw;
const doc = decodeURIComponent(body.doc);

const myOpenApiDocument = new Document(doc, Parsers.Yaml);
console.log(myOpenApiDocument);
return await this.spectral.run(myOpenApiDocument);

}

Is there any step missing in my usage?

Thanks
Devendra

Hey!

loadRuleset returns a promise, and in your case this promise is floating.
This means that by the time you run the linting process, the ruleset might be not loaded yet, and therefore you receive no results in the end.

class Linter {
  constructor(ruleSets) {
    this.ruleSets = ruleSets;
    this.spectral = new Spectral();
    this.spectral.registerFormat('oas2', isOpenApiv2);
    this.spectral.registerFormat('oas3', isOpenApiv3);

    this._oasRuleset = this.spectral.loadRuleset('spectral:oas');
  }

  async lint(raw) {
    await this._oasRuleset;

    const body = raw.body || raw;
    const doc = decodeURIComponent(body.doc);

    const myOpenApiDocument = new Document(doc, Parsers.Yaml);
    return await this.spectral.run(myOpenApiDocument);
  }
}

Could you try using the above example and see whether it does the trick?
Happy to help further in case it’s still broken.

Jakub