Skip to content

Instantly share code, notes, and snippets.

@rzane
Last active July 13, 2021 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rzane/c757a4fe7859160e89524b7eb8d57d73 to your computer and use it in GitHub Desktop.
Save rzane/c757a4fe7859160e89524b7eb8d57d73 to your computer and use it in GitHub Desktop.
Convert to TypedDocumentNode
# 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