Skip to content

Commit

Permalink
replace graphql datasource with apollo client (#160)
Browse files Browse the repository at this point in the history
* replace graphql datasource with apollo client

* add network mocking capabilities

* add more mocks

* Prevent accidental creation of multiple output channels

* add test for "wrong token" scenario

* changeset

* fix js types

* get one piece of real data into the mocks

* avoid `this.client.client.query`

* split mock server into functions
  • Loading branch information
phryneas authored Aug 2, 2024
1 parent a37cfaa commit 5312c6e
Show file tree
Hide file tree
Showing 19 changed files with 13,548 additions and 362 deletions.
5 changes: 5 additions & 0 deletions .changeset/dull-singers-melt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"vscode-apollo": patch
---

Replace `graphql-datasource` usage with `@apollo/client`
5 changes: 5 additions & 0 deletions .changeset/warm-mayflies-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"vscode-apollo": patch
---

Prevent accidental creation of multiple output channels
4 changes: 3 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"${workspaceFolder}/sampleWorkspace/sampleWorkspace.code-workspace"
],
"sourceMaps": true,
"env": { "APOLLO_ENGINE_ENDPOINT": "http://localhost:7096/apollo" },
"outFiles": ["${workspaceRoot}/lib/**/*.js"]
},
{
Expand All @@ -36,7 +37,8 @@
"${workspaceFolder}/sampleWorkspace/sampleWorkspace.code-workspace"
],
"outFiles": ["${workspaceFolder}/lib/**/*.js"],
"preLaunchTask": "BuildAndStartWorkspace"
"preLaunchTask": "BuildAndStartWorkspace",
"env": { "APOLLO_ENGINE_ENDPOINT": "http://localhost:7096/apollo" }
},
{
"name": "Attach to Test Debugger",
Expand Down
197 changes: 92 additions & 105 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"build": "tsc --build tsconfig.build.json",
"build:clean": "npm run build -- --clean",
"watch": "npm run build -- --watch",
"sampleWorkspace:run": "node sampleWorkspace/httpSchemaServer/server.mjs",
"sampleWorkspace:run": "node src/__e2e__/mockServer.js",
"changeset-version": "changeset version && npm i",
"changeset-publish": "npm run build && changeset publish",
"typecheck": "tsc --noEmit",
Expand All @@ -38,7 +38,6 @@
"@types/lz-string": "^1.3.34",
"@types/node-fetch": "2.6.11",
"@wry/equality": "^0.5.7",
"apollo-datasource": "^0.8.0",
"await-to-js": "^3.0.0",
"cosmiconfig": "^9.0.0",
"dotenv": "^16.0.0",
Expand Down Expand Up @@ -75,9 +74,11 @@
"@typescript-eslint/parser": "6.9.1",
"@vscode/test-cli": "^0.0.10",
"@vscode/test-electron": "^2.4.1",
"@wry/trie": "^0.5.0",
"eslint": "8.52.0",
"eslint-config-prettier": "9.0.0",
"eslint-plugin-prettier": "5.0.1",
"graphql-http": "^1.22.1",
"jest": "29.7.0",
"jest-environment-node": "29.7.0",
"memfs": "3.2.2",
Expand Down
58 changes: 0 additions & 58 deletions sampleWorkspace/httpSchemaServer/server.mjs

This file was deleted.

117 changes: 117 additions & 0 deletions src/__e2e__/mockServer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// @ts-check
const http = require("http");
const {
parseRequestParams,
createHandler,
} = require("graphql-http/lib/use/http");
const { buildSchema } = require("graphql");
const { Trie } = require("@wry/trie");

function runMockServer(
/** @type {number} */ port,
onStart = (/** @type {number} */ port) => {},
) {
const mocks = new Trie(false);

const server = http.createServer(async (req, res) => {
if (req.url === "/apollo") {
if (req.method === "POST") {
await handleApolloPost(req, res);
} else if (req.method === "PUT") {
await handleApolloPut(req, res);
}
} else if (req.url === "/graphql") {
schemaHandler(req, res);
} else {
res.writeHead(404).end();
}
});

server.on("error", (err) => {
console.log("Failed to start server", err);
});

console.log("Starting server...");
server.listen(port);
onStart(port);
console.log(`Server ready at: http://localhost:${port}`);
return {
[Symbol.dispose]() {
console.log("Closing server...");
server.close();
console.log("Server closed");
},
};

/**
* Mock GraphQL Endpoint Handler
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
async function handleApolloPost(req, res) {
const { operationName, variables } =
/** @type{import("graphql-http/lib/common").RequestParams} */ (
await parseRequestParams(req, res)
);

const mock = mocks.peek(operationName, JSON.stringify(variables));
if (mock) {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(mock.response));
} else {
console.warn("No mock available for %o", {
operationName,
variables,
});
res.writeHead(200).end(
JSON.stringify({
data: null,
errors: [
{
message: "No mock found.",
extensions: { operationName, variables },
},
],
}),
);
}
}

/**
* Handler to accept new GraphQL Mocks
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
async function handleApolloPut(req, res) {
const body = await new Promise((resolve) => {
let body = "";
req.setEncoding("utf-8");
req.on("data", (chunk) => (body += chunk));
req.on("end", () => resolve(body));
});
const { operationName, variables, response } = JSON.parse(body);
mocks.lookup(operationName, JSON.stringify(variables)).response = response;
//console.info("mock loaded", { operationName, variables });
res.end();
}
}

const schema = buildSchema(`#graphql
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`);
const schemaHandler = createHandler({
schema,
});

if (require.main === module) {
runMockServer(7096, require("./mocks.js").loadDefaultMocks);
}

module.exports.runMockServer = runMockServer;
Loading

0 comments on commit 5312c6e

Please sign in to comment.