All files / src/utils postalCode.ts

84.61% Statements 33/39
46.15% Branches 6/13
100% Functions 3/3
84.61% Lines 33/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63  1x             1x 4x 4x 4x 4x           1x 2x 2x 2x   2x 1x 1x   1x 1x 1x 1x       1x 1x 1x         1x 1x               1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x  
// src/utils/postalCode.ts
import postalCodeLib, { type JapanPostalCodeAddress } from 'japan-postal-code'
 
/**
 * 郵便番号を japan-postal-code 用に正規化する
 * - ハイフン・空白など非数字を除去
 * - 7桁にトリム
 */
export const normalizeJapanPostalCode = (raw: string): string => {
  if (!raw) return ''
  const digitsOnly = raw.replace(/[^\d]/g, '')
  return digitsOnly.slice(0, 7)
}
 
/**
 * japan-postal-code を Promise でラップした util
 * 7桁未満なら null を返す
 */
export const lookupJapanAddress = async (
  rawPostalCode: string,
): Promise<JapanPostalCodeAddress | null> => {
  const normalized = normalizeJapanPostalCode(rawPostalCode)
 
  if (normalized.length !== 7) {
    return null
  }
 
  return new Promise((resolve) => {
    try {
      postalCodeLib.get(normalized, (address) => {
        if (!address) {
          resolve(null)
          return
        }
        resolve(address)
      })
    } catch (e) {
      console.error(e)
      // 必要ならここで logger 呼び出しも可
      resolve(null)
    }
  })
}
 
/**
 * resume 用マッピング
 * - prefecture → administrativeArea
 * - city       → locality
 * - area+street → dependentLocality
 */
export const mapToAddressFormFields = (addr: JapanPostalCodeAddress) => {
  const prefecture = addr.prefecture ?? ''
  const city = addr.city ?? ''
  const area = addr.area ?? ''
  const street = addr.street ?? ''
 
  return {
    administrativeArea: prefecture,
    locality: city,
    dependentLocality: `${area}${street}`, // street が空なら area のみ
  }
}