Spring Boot

动态配置前端的一种处理方法

2020-04-27  本文已影响0人  EasyNetCN

首先架构设计不是凭空想象,也不能空中楼阁,脱离当前具体的业务和技术场景。

设计前端框架的时候,需要满足以下几个需求:

1:运行时发布和更新。

2:前端脚本版本管理。

3:统一并且灵活的配置。

4:便于本地测试。

配置项基于以下元素:

1:平台。平台可以为空,适用于所有平台。

2:页面。页面可以为空,适用于所有页面,多个页面时候,逗号分隔。

3:资源类型。分为通用资源,样式文件,脚本文件。

4:配置名称。

5:配置值。

6:排序

渲染的优先级:页面和平台->页面->平台

通用渲染页面

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport"
    content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title></title>
<link th:each="item:${cssList}" rel="stylesheet" th:href="${item}">
<script th:each="item:${jsList}" th:src="${item}"></script>
<script th:if="${null != page}" th:src="@{${staticJsCdnDir}+'/yd-'+${page}+'.js'}"></script>
</head>
<body>
    <div th:if="${null != page}" id="app">
        <th:block th:utext="@{'<yd-'+${page}+'/>'}"></th:block>
    </div>
</body>
<script th:if=${!#strings.isEmpty(page)}>
    iview.transfer=true;
    iview.lang='zh-CN';
    
    new Vue({
      el : '#app'
    });
</script>
</html>

渲染控制器

@Controller
public class HomeController {
    private static final Log logger = LogFactory.getLog(HomeController.class);

    private static final String PAGE_TEMPLATE = "home/page";

    private static final String STATIC_JS_URI_KEY = "staticJsCdnDir";

    @Value("${spring.profiles.active}")
    private String profile;

    @Autowired
    private SearchOperation<PageConfigSearchParam, Mono<List<PageConfig>>> appPageConfigSearchOperation;

    @Autowired
    private WebClient userServiceWebClient;

    @GetMapping("/login")
    public Mono<String> login(ServerHttpRequest request, Authentication authentication, Model model) {
        return null != authentication ? Mono.just("redirect:/")
                : combinePageConfig("login", model, authentication, false, request);
    }

    @GetMapping("")
    public Mono<String> index(ServerHttpRequest request, Authentication authentication, Model model) {
        return combinePageConfig("index", model, authentication, false, request);
    }

    @GetMapping(value = "/p/{component}")
    public Mono<String> viewComponent(ServerHttpRequest request, Authentication authentication,
            @PathVariable("component") String component, Model model) {
        return combinePageConfig(component, model, authentication, true, request);
    }

    private Mono<String> combinePageConfig(String component, Model model, Authentication authentication, boolean isPage,
            ServerHttpRequest request) {
        return appPageConfigSearchOperation.search(new PageConfigSearchParam()).flatMap(pageResult -> {
            var cssMap = new LinkedHashMap<String, LinkedHashMap<String, String>>();
            var jsMap = new LinkedHashMap<String, LinkedHashMap<String, String>>();

            processResourceMap(pageResult, cssMap, jsMap);
            processCssModel(model, component, cssMap);
            processJsModel(model, component, jsMap);

            if (StringUtils.isNotBlank(profile) && profile.toLowerCase().endsWith("-local")) {
                model.addAttribute(STATIC_JS_URI_KEY, "/js");
                model.addAttribute("page", component.toLowerCase());
            }

            if (null != authentication && isPage && StringUtils.isNotBlank(component)) {

                var userDetail = SecurityUtility.getUserDetails(authentication);

                return userServiceWebClient.get()
                        .uri("/enterprises/{enterpriseId}/users/{userId}/modules", userDetail.getEnterpriseId(),
                                userDetail.getUserId())
                        .retrieve().bodyToFlux(ModuleClientModel.class).filter(m -> StringUtils.isNotBlank(m.getUri())
                                && m.getUri().trim().equalsIgnoreCase("/p/" + component))
                        .any(module -> {
                            model.addAttribute("page", component.toLowerCase());
                            model.addAttribute("moduleId", module.getId());

                            return true;
                        }).flatMap(result -> Mono.just(PAGE_TEMPLATE));

            } else if (!isPage && StringUtils.isNotBlank(component)) {
                model.addAttribute("page", component.toLowerCase());

            }

            return Mono.just(PAGE_TEMPLATE);
        });
    }

    private void processResourceMap(List<PageConfig> pageResult,
            LinkedHashMap<String, LinkedHashMap<String, String>> cssMap,
            LinkedHashMap<String, LinkedHashMap<String, String>> jsMap) {
        if (null != pageResult && !pageResult.isEmpty()) {
            for (var item : pageResult) {
                if (null != item.getResourceType()) {
                    if (item.getResourceType() == 1 && !cssMap.containsKey(item.getName())) {
                        cssMap.put(item.getName(), new LinkedHashMap<String, String>());
                    } else if (item.getResourceType() == 2 && !jsMap.containsKey(item.getName())) {
                        jsMap.put(item.getName(), new LinkedHashMap<String, String>());
                    }

                    var pages = StringUtils.isEmpty(item.getPage()) ? new String[] { "" }
                            : StringUtils.split(item.getPage());

                    if (item.getResourceType() == 1) {
                        for (var p : pages) {
                            cssMap.get(item.getName()).put(p, item.getValue());
                        }
                    } else if (item.getResourceType() == 2) {
                        for (var p : pages) {
                            jsMap.get(item.getName()).put(p, item.getValue());
                        }
                    }

                }
            }
        }
    }

    private void processCssModel(Model model, String component,
            LinkedHashMap<String, LinkedHashMap<String, String>> cssMap) {
        var cssList = new ArrayList<String>(cssMap.size());

        for (var item : cssMap.values()) {
            if (StringUtils.isNotBlank(component) && item.containsKey(component)) {
                cssList.add(item.get(component));
            } else {
                var list = getList(item);

                if (!list.isEmpty()) {
                    cssList.add(list.get(0));
                }
            }
        }

        model.addAttribute("cssList", cssList);
    }

    private List<String> getList(LinkedHashMap<String, String> item) {
        var list = new ArrayList<String>(item.size());

        item.forEach((k, v) -> {
            if (k.isEmpty()) {
                list.add(v);
            }
        });

        return list;
    }

    private void processJsModel(Model model, String component,
            LinkedHashMap<String, LinkedHashMap<String, String>> jsMap) {
        var jsList = new ArrayList<String>(jsMap.size());

        jsMap.forEach((k, v) -> {
            if (k.equalsIgnoreCase("static-js-cdn-dir")) {
                if (StringUtils.isNotBlank(component) && v.containsKey(component)) {
                    model.addAttribute(STATIC_JS_URI_KEY, v.get(component));
                } else {
                    var list = getList(v);

                    if (!list.isEmpty()) {
                        model.addAttribute(STATIC_JS_URI_KEY, list.get(0));
                    }
                }
            } else {
                if (StringUtils.isNotBlank(component) && v.containsKey(component)) {
                    jsList.add(v.get(component));
                } else {
                    var list = getList(v);

                    if (!list.isEmpty()) {
                        jsList.add(list.get(0));
                    }
                }
            }
        });

        model.addAttribute("jsList", jsList);
    }
上一篇 下一篇

猜你喜欢

热点阅读