ScalaDataModelMapper.java 2.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
package com.kobylynskyi.graphql.codegen.scala;

import com.kobylynskyi.graphql.codegen.mapper.DataModelMapper;
import com.kobylynskyi.graphql.codegen.model.MappingContext;
import com.kobylynskyi.graphql.codegen.utils.Utils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

梦境迷离's avatar
梦境迷离 已提交
11 12
import static com.kobylynskyi.graphql.codegen.utils.Utils.wrapString;

13 14
public class ScalaDataModelMapper implements DataModelMapper {

15
    private static final String RESTRICTED_WORDS_WRAP_WITH = "`";
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    private static final Set<String> SCALA_RESTRICTED_KEYWORDS = new HashSet<>(Arrays.asList(
            "package", "import", "class", "object", "trait", "extends", "with", "type", "forSome",
            "private", "protected", "abstract", "sealed", "final", "implicit", "lazy", "override", "try",
            "catch", "finally", "throw", "if", "else", "match", "case", "do", "while", "for", "return", "yield",
            "def", "val", "var", "this", "super", "new", "true", "false", "null"
    ));

    //TODO maybe have others
    private static final Set<String> SCALA_RESTRICTED_METHOD_NAMES = new HashSet<>(Arrays.asList(
            "getClass", "notify", "notifyAll", "wait", "clone", "finalize"));


    @Override
    public String capitalizeIfRestricted(MappingContext mappingContext, String fieldName) {

        if (SCALA_RESTRICTED_KEYWORDS.contains(fieldName)) {
32
            return wrapString(fieldName, RESTRICTED_WORDS_WRAP_WITH);
33
        }
34 35 36 37 38 39

        // Scala case class's Fields cannot also use the names of these methods.
        if (SCALA_RESTRICTED_METHOD_NAMES.contains(fieldName)) {
            return Utils.capitalize(fieldName);
        }

40 41 42 43 44 45
        return fieldName;
    }

    @Override
    public String capitalizeMethodNameIfRestricted(MappingContext mappingContext, String methodName) {
        if (SCALA_RESTRICTED_KEYWORDS.contains(methodName)) {
46
            return wrapString(methodName, RESTRICTED_WORDS_WRAP_WITH);
47 48 49 50 51 52 53 54
        }
        if (SCALA_RESTRICTED_METHOD_NAMES.contains(methodName)) {
            return Utils.capitalize(methodName);
        }
        return methodName;
    }

}