Skip to content

Commit

Permalink
fix: #5 - Fixed an issue where there are alphanumeric parts in betwee…
Browse files Browse the repository at this point in the history
…n template variables were not separated properly.
  • Loading branch information
frontendr committed Nov 18, 2020
1 parent ffb909d commit 126675e
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"use strict";
import compress from "graphql-query-compress";

const GRAPHQL_KEY_START = /^[a-z]/i;
const GRAPHQL_TOKEN_START = /^[a-z]/i;
const GRAPHQL_TOKEN_END = /[a-z0-9]$/i;
const DEFAULT_COMMENT = "graphql";

export default function () {
Expand Down Expand Up @@ -73,12 +74,15 @@ export default function () {
* @param {{quasis: {value: {raw: string, cooked: string}}[], type: string}} node
*/
function compressTemplateLiteral(node) {
node.quasis.map(({ value }, index) => {
node.quasis.forEach(({ value, tail }, index) => {
const part = compress(value.raw).trim();
const prefix = index > 0 && part.match(GRAPHQL_KEY_START) ? " " : "";
// Multiple quasi's should be separated as they contain variables. (#4)
value.raw = prefix + part;
value.cooked = prefix + part;
// Multiple quasi's should be separated as they have variables next to them. (#4, #5)
const prefix =
index > 0 && (GRAPHQL_TOKEN_START.test(part) || part === "") ? " " : "";
const postfix = !tail && GRAPHQL_TOKEN_END.test(part) ? " " : "";
const compressed = prefix + part + postfix;
value.raw = compressed;
value.cooked = compressed;
});
}

Expand Down
4 changes: 4 additions & 0 deletions test/fixtures/literal-variables.expected.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,7 @@ const queryWithSpace = `{a(b:${ONE} c:true)}`;
const queryWithComma = `{a(b:${ONE},c:true)}`;
const queryWithTrailingVariable = `{a(b:${ONE} c:${TWO})}`;
const queryWithNewlines = `{a(b:${ONE} c:true)}`;
const NAME = "name";
const TYPE = "type";
const SPACE = " ";
const queryWithFragment = `fragment ${SPACE} ${NAME} on ${TYPE}{id name}`;
10 changes: 10 additions & 0 deletions test/fixtures/literal-variables.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,13 @@ const queryWithNewlines = /* GraphQL */ `{
c: true
)
}`;

const NAME = "name";
const TYPE = "type";
const SPACE = " ";

const queryWithFragment = /* GraphQL */ `fragment ${SPACE} ${NAME} on ${TYPE} {
id
name
}
`;

0 comments on commit 126675e

Please sign in to comment.