22
33module Data.Aeson.TypeScript.Formatting where
44
5+ import Data.Aeson as A
56import Data.Aeson.TypeScript.Types
7+ import qualified Data.ByteString.Lazy.Char8 as BL8
68import Data.Function ((&) )
79import qualified Data.List as L
810import Data.Maybe
@@ -23,15 +25,31 @@ formatTSDeclaration :: FormattingOptions -> TSDeclaration -> String
2325formatTSDeclaration (FormattingOptions {.. }) (TSTypeAlternatives name genericVariables names maybeDoc) =
2426 makeDocPrefix maybeDoc <> mainDeclaration
2527 where
26- mainDeclaration = case typeAlternativesFormat of
28+ mainDeclaration = case chooseTypeAlternativesFormat typeAlternativesFormat of
2729 Enum -> [i |#{exportPrefix exportMode}enum #{typeNameModifier name} { #{alternativesEnum} }|]
30+ where
31+ alternativesEnum = T. intercalate " , " $ [toEnumName entry | entry <- T. pack <$> names]
2832 EnumWithType -> [i |#{exportPrefix exportMode}enum #{typeNameModifier name}Enum { #{alternativesEnumWithType} }#{enumType}|]
33+ where
34+ alternativesEnumWithType = T. intercalate " , " $ [toEnumName entry <> " =" <> entry | entry <- T. pack <$> names]
35+ enumType = [i |\n\ntype #{name} = keyof typeof #{typeNameModifier name}Enum;|] :: T. Text
2936 TypeAlias -> [i |#{exportPrefix exportMode}type #{typeNameModifier name}#{getGenericBrackets genericVariables} = #{alternatives};|]
37+ where
38+ alternatives = T. intercalate " | " (fmap T. pack names)
39+
40+ -- Only allow certain formats if some checks pass
41+ chooseTypeAlternativesFormat Enum
42+ | all isDoubleQuotedString names = Enum
43+ | otherwise = TypeAlias
44+ chooseTypeAlternativesFormat EnumWithType
45+ | all isDoubleQuotedString names = EnumWithType
46+ | otherwise = TypeAlias
47+ chooseTypeAlternativesFormat x = x
48+
49+ isDoubleQuotedString s = case A. eitherDecode (BL8. pack s) of
50+ Right (A. String _) -> True
51+ _ -> False
3052
31- alternatives = T. intercalate " | " (fmap T. pack names)
32- alternativesEnum = T. intercalate " , " $ [toEnumName entry | entry <- T. pack <$> names]
33- alternativesEnumWithType = T. intercalate " , " $ [toEnumName entry <> " =" <> entry | entry <- T. pack <$> names]
34- enumType = [i |\n\ntype #{name} = keyof typeof #{typeNameModifier name}Enum;|] :: T. Text
3553 toEnumName = T. replace " \" " " "
3654
3755formatTSDeclaration (FormattingOptions {.. }) (TSInterfaceDeclaration interfaceName genericVariables (filter (not . isNoEmitTypeScriptField) -> members) maybeDoc) =
0 commit comments