Java里面的这个逻辑用NodeJS怎么写??
发布于 8 年前 作者 yjwkhhbj 3331 次浏览 来自 问答

Java代码

@RequestMapping("/tree")
@ResponseBody
public Object tree(Integer id) {
	if (id == null) {
		return render("error");
	}
	PersonEntity me = personEntityMapper.selectByPrimaryKey(id);
	if (me == null) {
		return render("error");
	}
	if (!StrKit.isBlank(me.getBabaId())) {
		PersonEntity baba = personEntityMapper.selectByPrimaryKey(StrKit.firstId(me.getBabaId()));
		if (baba != null)
			return render(personHtml(baba));
	}
	return render(personHtml(me));
}
public String personHtml(PersonEntity p) {
	String html = "<li><a><b>" + p.getName() + "</b> ";
	if (!StrKit.isBlank(p.getSpouseId())) {
		PersonEntity se = personEntityMapper.selectByPrimaryKey(StrKit.firstId(p.getSpouseId()));
		if (se != null)
			html += se.getName();
	}
	html += "</a>";
	List<PersonEntity> childs = null;
	if ("M".equals(p.getSex()))
		childs = personEntityMapper.findChildsByBabaId("" + p.getId());
	else
		childs = personEntityMapper.findChildsByMamaId("" + p.getId());
	if (childs != null && !childs.isEmpty()) {
		html += "<ul>";
		for (PersonEntity child : childs) {
			html += personHtml(child);
		}
		html += "</ul>";
	}
	return html += "</li>";
}
4 回复

粗略看了下你这段代码大致实现以下功能:

  • 页面渲染
  • 模型相关处理
  • 错误处理
  • 一些工具方法

对应Node里面可处理如下:

  • 页面渲染现在可考虑使用框架来处理如express/koa 或者单独的一些中间件处理页面渲染
  • 关于模型的处理可以参考orm2/sequelize 等
  • 错误处理可采用同步throws/try,catch, 异步callback, eventemitter等方式
  • Node辅助处理工具有很多如校验参数值的 validate 之类的

这个问题问得。。。。,怎么说呢,你直接问:我怎么写代码呢。感觉意思差不多!

if else 不加花括弧,不能忍。

回到顶部