Skip to content

Commit

Permalink
Add transform() moves
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Feb 20, 2022
1 parent 6c10ec3 commit 227e2cd
Showing 1 changed file with 34 additions and 5 deletions.
39 changes: 34 additions & 5 deletions src/config/normalize/lib/transform.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import isPlainObj from 'is-plain-obj'

import { callValueFunc, callUserFunc, getValidateExampleError } from './call.js'
import { resolvePath } from './path.js'

Expand All @@ -20,9 +22,13 @@ export const applyValidateTransform = async function ({

const valueA = await resolvePath({ value, path, glob, opts })
await validateValue(valueA, validate, opts)
const valueB = await transformValue(valueA, transform, opts)
const { value: valueB, newPath } = await transformValue(
valueA,
transform,
opts,
)
const name = await renameProp(valueB, rename, opts)
const newPaths = [name].filter(Boolean)
const newPaths = [newPath, name].filter(Boolean)
return { value: valueB, name, newPaths }
}

Expand All @@ -43,9 +49,32 @@ const validateValue = async function (value, validate, opts) {
// Apply `transform(value, opts)` which transforms the value set by the user.
// If can also delete it by returning `undefined`.
const transformValue = async function (value, transform, opts) {
return transform === undefined
? value
: await callValueFunc(transform, value, opts)
if (transform === undefined) {
return { value }
}

const transformReturn = await callValueFunc(transform, value, opts)

if (isTransformMove(transformReturn)) {
return getTransformMove(transformReturn, opts)
}

return { value: transformReturn }
}

// `transform()` can return a `{ newPath, value }` object to indicate the
// property name has been moved
const isTransformMove = function (transformReturn) {
return (
isPlainObj(transformReturn) &&
typeof transformReturn.newPath === 'string' &&
transformReturn.newPath !== '' &&
'value' in transformReturn
)
}

const getTransformMove = function ({ newPath, value }, { funcOpts: { name } }) {
return { newPath: `${name}.${newPath}`, value }
}

// Apply `rename(value, opts)` which transforms the property's name.
Expand Down

0 comments on commit 227e2cd

Please sign in to comment.