lib/enroute/export.rb in enroute-0.0.5 vs lib/enroute/export.rb in enroute-0.0.6
- old
+ new
@@ -52,31 +52,47 @@
def render_template
ERB.new(File.read("#{__dir__}/template.ts.erb")).result binding
end
def build_ts_args_definition(route)
- route[:segments].map do |segment|
+ args = route[:segments].each_with_object([]) do |segment, buffer|
type = route.dig(:typings, segment)&.chomp ||
config.dig(:typings, :_default, segment)&.chomp ||
"any"
optional = route[:requiredSegments].include?(segment) ? "" : "?"
- "#{segment.camelize(:lower)}#{optional}: #{type}"
- end.join(", ")
+
+ buffer << "#{segment.camelize(:lower)}#{optional}: #{type}"
+ end
+
+ args << "params?: Record<string, unknown>"
+
+ "args?: {#{args.join('; ')}}"
+
+ # (args + ["params: Record<string, unknown> = {}"]).join(", ")
end
def build_ts_handler_function(route)
args = JSON.pretty_generate(route.except(:typings))
%[const #{route[:name]}Handler = buildRoute(#{args});]
end
def build_ts_route_function(route)
args = build_ts_args_definition(route)
+
segments = route[:segments].map {|segment| segment.camelize(:lower) }
+ destruct = [segments.join(", "), "params"].reject(&:blank?).join(", ")
- [
- %[export const #{route[:name]}Url = (#{args}): string =>],
- %[ #{route[:name]}Handler(#{segments.join(', ')});]
- ].join("\n")
+ <<~TYPESCRIPT
+ export function #{route[:name]}Url(#{args}): string {
+ const {#{destruct}} = args ?? {};
+ return buildUrl(#{route[:name]}Handler(#{segments.join(', ')}), params ?? {}).url;
+ }
+
+ export function #{route[:name]}Path(#{args}): string {
+ const {#{destruct}} = args ?? {};
+ return buildUrl(#{route[:name]}Handler(#{segments.join(', ')}), params ?? {}).path;
+ }
+ TYPESCRIPT
end
end
end