Skip to content

Instantly share code, notes, and snippets.

@ohgyun
Created August 14, 2013 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ohgyun/6229433 to your computer and use it in GitHub Desktop.
Save ohgyun/6229433 to your computer and use it in GitHub Desktop.
/**
* 데이터 타입을 미리 정의하고, 전달받은 데이터에서 타입에 맞는 값을 받아 설정한다.
* 타입 정의는 JSON 형태로 하며, 객체에 설정한 키값을 {{ }} 안에 dot으로 패스를 구분해 넣는다.
* {
* '전달받을 데이터의 키': '{{dot으로 구분한 키값}}',
* }
*
* @param {Object} context
* @param {Object} data
* @param {Object} typeDef
* @example
*
* var user = {};
* var type = {
* userId: '{{id}}', // 전달받은 데이터의 userId 값을 객체의 id로 설정한다.
* userName: '{{name}}',
* phone: '{{additional.phone}}' // 전달받은 데이터의 phone을 객체의 additional.phone에 설정한다.
* };
* populate(user, {
* userId: '1234',
* userName: 'steve',
* phone: '1234-1234'
* });
*
* user; //--> { id: '1234', name: 'steve', additional: { phone: '1234-1234' } }
*/
function populate(context, data, typeDef) {
var rKey = /^\{\{([\w.]+)\}\}$/;
var typeKey; // 타입의 키
var typeValue; // 타입의 값
var origKey; // 원본의 키
var errMsg = 'Invalid type definition: "{{typeKey}}: {{typeValue}}"';
for (typeKey in typeDef) {
if (typeDef.hasOwnProperty(typeKey)) {
typeValue = typeDef[typeKey];
// 타입 정의가 문자열일 경우 치환
if (typeof typeValue === 'string' && rKey.test(typeValue)) {
if (data && data[typeKey]) { // 데이터가 존재할 경우에만 덮어쓴다.
origKey = RegExp.$1;
this.setObject(context, origKey, data[typeKey]);
}
// 객체인 경우 재귀 호출한다.
} else if (typeof typeValue === 'object') {
this.populate(context, data[typeKey], typeValue);
} else {
throw new Error(this.format(errMsg, {
typeKey: typeKey,
typeValue: typeValue
}));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment