メインコンテンツまでスキップ
バージョン: 🚧 Canary

📮 Japan Post Driver

The Japan Post driver integrates with the Japan Post Digital Address API (v1) for postal-code address lookup. It handles OAuth2 client-credentials authentication, token caching, and response normalization.

Use it with the Address Service by injecting the driver as findAddressDriver.


🎯 Overview

import {drivers} from '@nodeblocks/backend-sdk';

const {createJapanPostDriver} = drivers;

const findAddressDriver = createJapanPostDriver(
process.env.JAPAN_POST_CLIENT_ID!,
process.env.JAPAN_POST_SECRET_KEY!,
process.env.JAPAN_POST_HOSTNAME, // optional; defaults to 'api.da.pf.japanpost.jp'
);

📋 Available Japan Post Driver

createJapanPostDriver

Creates a Japan Post address lookup driver. This is a synchronous factory — no await is required.

Parameters:

ParameterTypeDefaultDescription
clientIdstringClient ID for the Japan Post Digital Address API
secretKeystringSecret key for the Japan Post Digital Address API
hostname?string'api.da.pf.japanpost.jp'API hostname (use sandbox hostname for testing)

Returns: JapanPostDriver — Driver object with findAddress(postalCode)

Usage:

import {drivers} from '@nodeblocks/backend-sdk';

const {createJapanPostDriver} = drivers;

const driver = createJapanPostDriver(
process.env.JAPAN_POST_CLIENT_ID!,
process.env.JAPAN_POST_SECRET_KEY!,
process.env.JAPAN_POST_HOSTNAME,
);

const address = await driver.findAddress('100-0001');
// { prefecture: '東京都', city: '千代田区', town: '千代田', postalCode: '1000001' }

JapanPostDriver

Type alias defined in SDK source (src/drivers/japan-post.ts) as ReturnType<typeof createJapanPostDriver>:

type JapanPostDriver = {
findAddress(postalCode: string): Promise<{
prefecture: string;
city: string;
town?: string;
postalCode: string;
} | null>;
};

The type is exported from the drivers namespace. JapanPostDriver satisfies the FindAddressDriver contract from src/blocks/address.ts, which the Address Service injects as findAddressDriver. The driver returns null for a missing lookup; the Address block converts that value into err(new AddressNotFoundError('No matching address found.')).

findAddress

Looks up a Japanese address by postal code.

ParameterTypeDescription
postalCodestringPostal code with or without hyphens (must normalize to 7 digits)

Returns: Promise<{ prefecture: string; city: string; town?: string; postalCode: string } | null>

OutcomeBehavior
Address found{ prefecture, city, town?, postalCode }postalCode comes from the API zip_code field (first address entry)
Not found (HTTP 404)null
Empty addresses array (HTTP 200)null
Invalid formatThrows Error: Invalid postal code format: "${postalCode}". Expected 7 digits (hyphens allowed).
API error (valid error schema)Throws Error(data.message)
Token/response schema mismatchThrows Error('Japan Post driver error.', { cause })

Behavior details:

  • Strips hyphens before validation and API request
  • Validates normalized postal code matches /^\d{7}$/
  • Token and address responses are validated with AJV schemas before returning
  • Obtains OAuth2 token via POST https://{hostname}/api/v1/j/token with body { client_id, grant_type: 'client_credentials', secret_key }; caches token until accessTokenExpiresAt, refreshed when expired
  • Looks up address via GET /api/v1/searchcode/{postalCode}?searchtype=2 with Authorization: Bearer {token}
  • Sets town only when all returned addresses share a single town name (excludes '以下に掲載がない場合')

Normalization through Address Service: The address block (findAddress in src/blocks/address.ts) strips hyphens before calling the driver, then the driver validates /^\d{7}$/ again. Direct driver calls accept hyphenated input; calls routed through the Address Service arrive at the driver already normalized.

Examples:

await driver.findAddress('100-0001'); // with hyphens
await driver.findAddress('1000001'); // without hyphens
await driver.findAddress('999-9999'); // null — not found

await driver.findAddress('12');
// throws Error: Invalid postal code format: "12". Expected 7 digits (hyphens allowed).

🔧 Using Japan Post Driver

With Services

Inject the driver via the third-argument options on addressService:

import {services, drivers, utils} from '@nodeblocks/backend-sdk';

const {addressService} = services;
const {createJapanPostDriver} = drivers;
const {createCache} = utils;

const findAddressDriver = createJapanPostDriver(
process.env.JAPAN_POST_CLIENT_ID!,
process.env.JAPAN_POST_SECRET_KEY!,
process.env.JAPAN_POST_HOSTNAME,
);

addressService(
{identities},
{
authSecrets: {
authEncSecret: process.env.AUTH_ENC_SECRET!,
authSignSecret: process.env.AUTH_SIGN_SECRET!,
},
findAddressCache: createCache(),
},
{findAddressDriver},
);

See Address Service for full Express wiring, authentication, and cache configuration.