Last active
January 21, 2019 06:16
-
-
Save jacknie84/652f7e592626b90d772bc2549f275b4b to your computer and use it in GitHub Desktop.
The script is sutiable for spring-mvc. 스프링 MVC에 알맞은 파라미터 쿼리 문자열을 만들어주는 스크립트.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function serializeParam(name, value) { | |
if (typeof value === "object" && value !== null) { | |
var stack = []; | |
if (isIndexable(value)) { | |
for (var index in value) { | |
if (!isMetadataProperty(index)) { | |
var indexName = getIndexName(name, index); | |
var serialized = serializeParam(indexName, value[index]); | |
if (serialized) { | |
stack.push(serialized); | |
} | |
} | |
} | |
} | |
else { | |
for (var key in value) { | |
if (!isMetadataProperty(key)) { | |
var propName = getReferenceName(name, key); | |
var serialized = serializeParam(propName, value[key]); | |
if (serialized) { | |
stack.push(serialized); | |
} | |
} | |
} | |
} | |
return stack.join("&"); | |
} | |
else if (["number", "boolean"].indexOf(typeof value) >= 0) { | |
return encodeURIComponent(name) + "=" + value; | |
} | |
else { | |
if (value) { | |
return encodeURIComponent(name) + "=" + encodeURIComponent(value); | |
} | |
else { | |
return null; | |
} | |
} | |
} | |
function getReferenceName(parentProperty, childProperty) { | |
if (typeof parentProperty === "string" && parentProperty.length > 0) { | |
if (isValidPropertyNames(parentProperty, childProperty)) { | |
return uncapitalize(parentProperty) + "." + uncapitalize(childProperty); | |
} | |
throw new Error("유효하지 않은 프로퍼티 이름(parentProperty: [" + parentProperty + "], childProperty: [" + childProperty + "])입니다."); | |
} | |
else { | |
if (isValidPropertyNames(childProperty)) { | |
return uncapitalize(childProperty); | |
} | |
throw new Error("유효하지 않은 프로퍼티 이름(childProperty: [" + childProperty + "])입니다."); | |
} | |
} | |
function isIndexable(value) { | |
return Array.isArray(value) || value["@type"] === "map"; | |
} | |
function isMetadataProperty(name) { | |
return name.indexOf("@") === 0; | |
} | |
function getIndexName(targetName, index) { | |
if (!isValidPropertyNames(targetName)) { | |
throw new Error("유효하지 않은 프로퍼티 이름(targetName: [" + targetName + "])입니다."); | |
} | |
return targetName + "[" + index + "]"; | |
} | |
function isValidPropertyNames() { | |
var regexp = /^[a-zA-Z\$_][\w\$\.\[\]]+$/; | |
for (var i = 0; i < arguments.length; i++) { | |
if (typeof arguments[i] !== "string" || !regexp.test(arguments[i])) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function uncapitalize(string) { | |
var firstChar = string.charAt(0); | |
return firstChar.toLowerCase() + string.substring(1, string.length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment