Last active
July 13, 2021 18:06
-
-
Save rzane/c757a4fe7859160e89524b7eb8d57d73 to your computer and use it in GitHub Desktop.
Convert to TypedDocumentNode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Convert your codebase to use TypedDocumentNode. It's not perfect, but | |
# it does a pretty decent job. You'll want to review the changes manually. | |
# Usage: ruby convert.rb [...GLOBS] | |
# Example: ruby convert.rb "src/**/*.{ts,tsx}" | |
require "set" | |
def convert_import(line) | |
parts = line.scan(/use(\w+)(Query|Mutation)/) | |
return [line] if parts.empty? | |
use = Set.new | |
docs = Set.new | |
path = line.match(/"(.*)"/)[1] | |
parts.each do |name, type| | |
use << "use#{type}" | |
docs << "#{name}Document" | |
end | |
[ | |
%(import { #{use.join(", ")} } from "@apollo/client";\n), | |
%(import { #{docs.join(", ")} } from "#{path}";\n) | |
] | |
end | |
def convert(lines) | |
lines.flat_map do |line| | |
if line.start_with?("import") | |
convert_import(line) | |
else | |
find = /use(\w+)(Query|Mutation)\(/ | |
replace = "use\\2(\\1Document, " | |
[line.sub(find, replace).sub("Document, );", "Document);")] | |
end | |
end | |
end | |
Dir.glob(ARGV) do |path| | |
lines = File.readlines(path) | |
lines = convert(lines) | |
File.write path, lines.join | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment