Skip to content

Commit

Permalink
added support for async service creation
Browse files Browse the repository at this point in the history
Its now possible to do things like:

fastify.register(require("fastify-openapi-glue"), {
  specification: `${__dirname}/petstore-swagger.v2.json`,
  service: async () => {
    const dataProvider = await DataStore.create();
    return new Service(dataProvider);
  }
});
  • Loading branch information
Hans Klunder committed Oct 16, 2019
1 parent 7fd9973 commit bf10721
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function getObject(param) {
data = data();
}

return data;
return Promise.resolve(data);
}

// fastify uses the built-in AJV instance during serialization, and that
Expand All @@ -38,7 +38,7 @@ function stripResponseFormats(schema) {
}

async function fastifyOpenapiGlue(instance, opts) {
const service = getObject(opts.service);
const service = await getObject(opts.service);
if (!isObject(service)) {
throw new Error("'service' parameter must refer to an object");
}
Expand Down
3 changes: 3 additions & 0 deletions test/async-service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// async service provider example
const service = require("./service.js");
module.exports = async opts => new Promise(resolve => resolve(service(opts)));
21 changes: 21 additions & 0 deletions test/test-plugin.v3.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ const missingServiceOpts = {
service: `${__dirname}/not-a-valid-service.js`
};

const asyncServiceOpts = {
specification: testSpec,
service: `${__dirname}/async-service.js`
};

const petStoreOpts = {
specification: petStoreSpec,
service
Expand Down Expand Up @@ -339,6 +344,22 @@ test("invalid service definition throws error ", t => {
});
});

test("async service definition does not throw error", t => {
t.plan(2);
const fastify = Fastify();
fastify.register(fastifyOpenapiGlue, asyncServiceOpts);
fastify.inject(
{
method: "GET",
url: "/pathParam/2"
},
(err, res) => {
t.error(err);
t.strictEqual(res.statusCode, 200);
}
);
});

test("full pet store V3 definition does not throw error ", t => {
t.plan(1);
const fastify = Fastify();
Expand Down

0 comments on commit bf10721

Please sign in to comment.