Last active
January 13, 2019 23:25
-
-
Save jmserrano-dev/ca87690ea2d852bb8b5e3d62739b6ab2 to your computer and use it in GitHub Desktop.
Utils to convert translations files (json format) to Typescript declaration (d.ts) [linq] [script]
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
////////////// JSON EXAMPLE | |
// { | |
// "title": "My title", | |
// "form": { | |
// "title": "My form", | |
// "buttons": { | |
// "send": "Enviar", | |
// "cancel": "Cancelar", | |
// "others": { | |
// "other": "<>" | |
// } | |
// } | |
// } | |
// } | |
void Main() | |
{ | |
// TODO: Add library for process args from prompt | |
// -i Path input | |
// -o Path output | |
// -ns Namespace | |
// -md Module | |
var json = File.ReadAllText("REPLACE_PATH"); | |
dynamic parsedObject = JsonConvert.DeserializeObject(json); | |
var result = new List<string>(); | |
ProcessJsonObject(parsedObject, string.Empty, ref result); | |
var deraclaration = GetTypescriptDeclaration(result); | |
Console.WriteLine(deraclaration); | |
} | |
// Refactor to Template class | |
static string TemplateMethod(string key) => $"t(_: \"{key}\"): string;"; | |
static string TemplateDeclaration( | |
IReadOnlyList<string> methods, | |
string moduleName = "typed-i18n", | |
string namespaceName = "Namespace") => | |
$@" | |
declare module '{moduleName}' {{ | |
export interface I{namespaceName}Translation {{ | |
{string.Join("\n", methods)} | |
}} | |
}}"; | |
static string GetTypescriptDeclaration(IReadOnlyList<string> keys) | |
{ | |
var methods = new List<string>(); | |
foreach (var key in keys) methods.Add(TemplateMethod(key)); | |
return TemplateDeclaration(methods); | |
} | |
// Refactor to Processing class | |
static void ProcessJsonObject(dynamic obj, string parent, ref List<string> result) | |
{ | |
foreach (dynamic entry in obj) | |
{ | |
string key = entry.Name; | |
dynamic value = entry.Value; | |
if (value is JObject) ProcessJsonObject(value, GetParent(parent, key), ref result); | |
else result.Add(GetParent(parent, key)); | |
} | |
} | |
static string GetParent(string parent, string child) => | |
string.IsNullOrEmpty(parent) | |
? $"{child}" | |
: $"{parent}.{child}"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment