Created
April 22, 2020 09:38
-
-
Save juzhiyuan/d1c36742cc7864beea2bcd7f20ed4b91 to your computer and use it in GitHub Desktop.
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
import {parse} from 'query-string' | |
import sha256 from 'crypto-js/sha256' | |
import cloneDeep from 'lodash.clonedeep' | |
const deepSort = (data = {}) => | |
Object.keys(data) | |
.sort() | |
.reverse() | |
.map(key => { | |
if (data[key] === null) { | |
data[key] = 'null' | |
} else if (Array.isArray(data[key])) { | |
data[key] = data[key].map(deepSort) | |
} else if (data[key] === Object(data[key])) { | |
data[key] = deepSort(data[key]) | |
} | |
return {[key]: data[key]} | |
}) | |
.reduce((prev, current) => ({...prev, ...current}), {}) | |
const calcStr = (path = '', data = {}) => { | |
let str = '' | |
Object.entries(data).forEach(([key, value], index) => { | |
if (Array.isArray(value) || value === Object(value)) { | |
value = JSON.stringify(value).replace(/"/g, '') | |
} | |
str += `${key}=${value}${index % 2 ? '&' : '|'}` | |
}) | |
return `${path}^${str.slice(0, -1)}^` | |
} | |
const calcSignature = (path = '', query = '', body: any = {}) => { | |
const requestId = Math.random().toString(36).slice(2) | |
const timestamp = Math.round(new Date().getTime()) | |
const headers = { | |
'X-RequestId': requestId, | |
'X-Timestamp': timestamp.toString(), | |
} | |
const str = calcStr( | |
path, | |
deepSort({ | |
...headers, | |
...parse(query), | |
...cloneDeep(body), | |
}) | |
) | |
return { | |
...headers, | |
'X-Signature': sha256(str).toString(), | |
} | |
} | |
export default calcSignature |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment