Skip to content

Commit

Permalink
Inserting cors
Browse files Browse the repository at this point in the history
  • Loading branch information
andrelmlins committed Jul 18, 2020
1 parent 6a0cf7d commit 79db63d
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
],
"dependencies": {
"apollo-server-fastify": "^2.15.1",
"fastify": "^2.15.2"
"fastify": "^2.15.2",
"fastify-cors": "3.x"
},
"devDependencies": {
"typescript": "^3.9.7"
Expand Down
26 changes: 23 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fastify, { FastifyRequest } from 'fastify';
import fastify, { FastifyRequest, FastifyInstance } from 'fastify';
import { ApolloServer, IResolvers } from 'apollo-server-fastify';
import { ApolloServerBase, Context, Config } from 'apollo-server-core';
import { DocumentNode } from 'graphql';
Expand All @@ -16,14 +16,34 @@ type ListenParams = {
};

class RecifeFastify {
app = fastify({ logger: true });
app: FastifyInstance;

constructor(bodyParserConfig: any, corsConfig: any, homepage: string) {
this.app = fastify({ logger: true });

if (corsConfig && corsConfig.enabled) {
this.app.register(
require('fastify-cors'),
this.corsTranslator(corsConfig)
);
}

constructor(bodyParser: any, cors: any, homepage: string) {
this.app.get('/', (_, reply) => {
reply.send(homepage);
});
}

private corsTranslator(corsConfig: any) {
return {
origin: corsConfig.origin,
methods: corsConfig.allowMethods,
allowedHeaders: corsConfig.allowHeaders,
exposedHeaders: corsConfig.exposeHeaders,
credentials: corsConfig.credentials,
maxAge: corsConfig.maxAge
};
}

createApolloServer({
typeDefs,
resolvers,
Expand Down
10 changes: 9 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,14 @@ fastify-accepts@^1.0.0:
accepts "^1.3.5"
fastify-plugin "^1.2.0"

fastify-cors@3.x:
version "3.0.3"
resolved "https://registry.yarnpkg.com/fastify-cors/-/fastify-cors-3.0.3.tgz#c1b2227983d7b02feff73fd642d81041adfbe124"
integrity sha512-SDMa+GtyTTAU7pWZwY4fukb/VwCZ4c30p0oEaE7/d/+VCvceB1+NzW2udp2dSZZfWR7J1kUookCpw2dLmtAsSw==
dependencies:
fastify-plugin "^1.6.0"
vary "^1.1.2"

fastify-cors@^0.2.0:
version "0.2.0"
resolved "https://registry.yarnpkg.com/fastify-cors/-/fastify-cors-0.2.0.tgz#8fce0a2a5ba05ac08c7d6f2ca4c501b0ae638e39"
Expand All @@ -632,7 +640,7 @@ fastify-cors@^0.2.0:
fastify-plugin "^1.2.0"
vary "^1.1.2"

fastify-plugin@^1.2.0:
fastify-plugin@^1.2.0, fastify-plugin@^1.6.0:
version "1.6.1"
resolved "https://registry.yarnpkg.com/fastify-plugin/-/fastify-plugin-1.6.1.tgz#122f5a5eeb630d55c301713145a9d188e6d5dd5b"
integrity sha512-APBcb27s+MjaBIerFirYmBLatoPCgmHZM6XP0K+nDL9k0yX8NJPWDY1RAC3bh6z+AB5ULS2j31BUfLMT3uaZ4A==
Expand Down

0 comments on commit 79db63d

Please sign in to comment.