서버 응답을 표 행으로 바꾸기Map a server response to grid rows
서버마다 같은 데이터를 다른 모양(중첩된 항목, 글자로 온 숫자, 평평한 목록, 페이지에 심어 둔 JSON)으로 보내요. 하나의 변환 코드가 모두 같은 행 목록으로 바꾸고, 값이 없거나 망가진 항목은 오류 대신 빈 값이나 건너뜀으로 처리해요.Servers send the same data in different shapes: nested items, numbers as text, flat lists, JSON embedded in the page. One conversion step maps them all to the same rows, and missing or broken items become empty values or are skipped instead of failing.
코드Code
탭을 골라 코드를 복사하세요. 위 화면은 이 코드를 그대로 실행한 결과예요.Pick a tab and copy the code. The preview above runs exactly this code.
이 화면은 새 모양 옵션을 켠 모양이에요: density: 'spacious', iconStyle: 'soft', motion: true (코드에 없으면 기본 모양으로 보여요)This preview has the new-look options on: density: 'spacious', iconStyle: 'soft', motion: true (without them in your code you get the default look)
버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<div id="app">
<div class="toolbar">
<select aria-label="응답 모양" id="load">
<option value="nested" selected>중첩된 응답 (기본)</option>
<option value="flat">평평한 목록</option>
<option value="embedded">페이지에 심은 JSON</option>
<option value="failure">실패 응답</option>
</select>
</div>
<div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('load').addEventListener('change', (event) => actions.load(api, event.target.value));// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
export const options = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'hired',
title: '입사일',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: '월급(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// 서버마다 같은 데이터를 다른 모양으로 보내요: 이름이 중첩되고 값이 글자인 응답, 평평한 목록,
// 페이지 안에 JSON으로 심어 둔 데이터(일부러 망가뜨린 줄 두 개 포함), 그리고 실패 응답이에요.
const RESPONSES = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: '김민준',
dept: { code: 'D10', name: '개발팀' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: '이서연',
dept: { code: 'D20', name: '디자인팀' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: '박지호', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: '최유나', dept: '영업팀', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: '정도윤', dept: '인사팀', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: '한소희', dept: '개발팀', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: '오세훈', dept: '영업팀', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: '금액이 글자', dept: '개발팀', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: '없는 날짜', dept: '개발팀', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: L('로그인이 만료됐어요. 다시 로그인해 주세요.', 'Your session has expired. Please sign in again.'),
},
};
// 'YYYY-MM-DD'는 달력 날짜예요. new Date(글자)는 UTC로 읽어서 하루가 밀릴 수 있어서 연·월·일로 만들어요.
function toDate(text) {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value) => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say = () => { };
export function setup(api, log) {
say = log;
// 선택 목록의 기본값('중첩된 응답')을 열자마자 불러와서, 표가 비어 있지 않게 해요.
load(api, 'nested');
return () => { };
}
/** 응답 모양이 달라도 같은 Row 목록으로 바꿔요. 값이 없거나 망가진 필드는 예외가 아니라 빈 값이 돼요. */
function mapResponse(body, kind) {
skipped = 0;
const record = body;
if (Array.isArray(body)) {
const rows = [];
for (const item of body) {
const date = toDate(item['hired']);
// 직접 심어 둔 JSON은 한 줄씩 검사해서 통과한 줄만 넣어요.
if (kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK')
throw new Error(record.message ?? '요청이 실패했어요');
return (record.data?.items ?? []).map((item) => {
const r = item;
const dept = r['dept'];
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api, kind) {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say({
ko: `${rows.length}행을 넣었어요` + (skipped ? ` (망가진 ${skipped}줄은 건너뛰었어요)` : ''),
en: `Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''),
});
}
catch (error) {
// 빈 표만 보여 주지 않고, 서버가 준 메시지를 빈 목록 문구로 보여 줘요.
api.setRows([]);
const message = error instanceof Error ? error.message : '오류';
api.setOptions({ messages: { noRows: message } });
say({ ko: `실패: ${message}`, en: `Failed: ${message}` });
}
}
export const actions = {
load: (api, value) => load(api, value ?? 'nested'),
};<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>서버 응답을 표 행으로 바꾸기</title>
</head>
<body>
<div class="toolbar">
<select aria-label="응답 모양" id="load">
<option value="nested" selected>중첩된 응답 (기본)</option>
<option value="flat">평평한 목록</option>
<option value="embedded">페이지에 심은 JSON</option>
<option value="failure">실패 응답</option>
</select>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko, en) => document.documentElement.dataset.lang === 'en' ? en : ko;
const options = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'hired',
title: '입사일',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: '월급(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// 서버마다 같은 데이터를 다른 모양으로 보내요: 이름이 중첩되고 값이 글자인 응답, 평평한 목록,
// 페이지 안에 JSON으로 심어 둔 데이터(일부러 망가뜨린 줄 두 개 포함), 그리고 실패 응답이에요.
const RESPONSES = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: '김민준',
dept: { code: 'D10', name: '개발팀' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: '이서연',
dept: { code: 'D20', name: '디자인팀' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: '박지호', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: '최유나', dept: '영업팀', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: '정도윤', dept: '인사팀', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: '한소희', dept: '개발팀', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: '오세훈', dept: '영업팀', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: '금액이 글자', dept: '개발팀', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: '없는 날짜', dept: '개발팀', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: L('로그인이 만료됐어요. 다시 로그인해 주세요.', 'Your session has expired. Please sign in again.'),
},
};
// 'YYYY-MM-DD'는 달력 날짜예요. new Date(글자)는 UTC로 읽어서 하루가 밀릴 수 있어서 연·월·일로 만들어요.
function toDate(text) {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value) => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say = () => { };
function setup(api, log) {
say = log;
// 선택 목록의 기본값('중첩된 응답')을 열자마자 불러와서, 표가 비어 있지 않게 해요.
load(api, 'nested');
return () => { };
}
/** 응답 모양이 달라도 같은 Row 목록으로 바꿔요. 값이 없거나 망가진 필드는 예외가 아니라 빈 값이 돼요. */
function mapResponse(body, kind) {
skipped = 0;
const record = body;
if (Array.isArray(body)) {
const rows = [];
for (const item of body) {
const date = toDate(item['hired']);
// 직접 심어 둔 JSON은 한 줄씩 검사해서 통과한 줄만 넣어요.
if (kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK')
throw new Error(record.message ?? '요청이 실패했어요');
return (record.data?.items ?? []).map((item) => {
const r = item;
const dept = r['dept'];
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api, kind) {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say({
ko: `${rows.length}행을 넣었어요` + (skipped ? ` (망가진 ${skipped}줄은 건너뛰었어요)` : ''),
en: `Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''),
});
}
catch (error) {
// 빈 표만 보여 주지 않고, 서버가 준 메시지를 빈 목록 문구로 보여 줘요.
api.setRows([]);
const message = error instanceof Error ? error.message : '오류';
api.setOptions({ messages: { noRows: message } });
say({ ko: `실패: ${message}`, en: `Failed: ${message}` });
}
}
const actions = {
load: (api, value) => load(api, value ?? 'nested'),
};
options.ariaLabel = "서버 응답을 표 행으로 바꾸기";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('load').addEventListener('change', (event) => actions.load(api, event.target.value));
</script>
</body>
</html>버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="응답 모양"
disabled={!api}
onChange={(event) => api && actions.load(api, event.target.value)}
>
<option value="nested">중첩된 응답 (기본)</option>
<option value="flat">평평한 목록</option>
<option value="embedded">페이지에 심은 JSON</option>
<option value="failure">실패 응답</option>
</select>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
hired: Date;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'hired',
title: '입사일',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: '월급(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// 서버마다 같은 데이터를 다른 모양으로 보내요: 이름이 중첩되고 값이 글자인 응답, 평평한 목록,
// 페이지 안에 JSON으로 심어 둔 데이터(일부러 망가뜨린 줄 두 개 포함), 그리고 실패 응답이에요.
const RESPONSES: Record<string, unknown> = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: '김민준',
dept: { code: 'D10', name: '개발팀' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: '이서연',
dept: { code: 'D20', name: '디자인팀' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: '박지호', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: '최유나', dept: '영업팀', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: '정도윤', dept: '인사팀', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: '한소희', dept: '개발팀', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: '오세훈', dept: '영업팀', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: '금액이 글자', dept: '개발팀', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: '없는 날짜', dept: '개발팀', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: L(
'로그인이 만료됐어요. 다시 로그인해 주세요.',
'Your session has expired. Please sign in again.',
),
},
};
// 'YYYY-MM-DD'는 달력 날짜예요. new Date(글자)는 UTC로 읽어서 하루가 밀릴 수 있어서 연·월·일로 만들어요.
function toDate(text: unknown): Date {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value: unknown): number => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// 선택 목록의 기본값('중첩된 응답')을 열자마자 불러와서, 표가 비어 있지 않게 해요.
load(api, 'nested');
return () => {};
}
/** 응답 모양이 달라도 같은 Row 목록으로 바꿔요. 값이 없거나 망가진 필드는 예외가 아니라 빈 값이 돼요. */
function mapResponse(body: unknown, kind: string): Row[] {
skipped = 0;
const record = body as { code?: string; message?: string; data?: { items?: unknown[] } };
if (Array.isArray(body)) {
const rows: Row[] = [];
for (const item of body as Record<string, unknown>[]) {
const date = toDate(item['hired']);
// 직접 심어 둔 JSON은 한 줄씩 검사해서 통과한 줄만 넣어요.
if (
kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))
) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK') throw new Error(record.message ?? '요청이 실패했어요');
return (record.data?.items ?? []).map((item) => {
const r = item as Record<string, unknown>;
const dept = r['dept'] as { name?: string } | null;
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api: GridApi<Row>, kind: string): void {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say({
ko: `${rows.length}행을 넣었어요` + (skipped ? ` (망가진 ${skipped}줄은 건너뛰었어요)` : ''),
en: `Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''),
});
} catch (error) {
// 빈 표만 보여 주지 않고, 서버가 준 메시지를 빈 목록 문구로 보여 줘요.
api.setRows([]);
const message = error instanceof Error ? error.message : '오류';
api.setOptions({ messages: { noRows: message } });
say({ ko: `실패: ${message}`, en: `Failed: ${message}` });
}
}
export const actions = {
load: (api: GridApi<Row>, value?: string) => load(api, value ?? 'nested'),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="응답 모양"
:disabled="!api"
@change="api && actions.load(api, ($event.target as HTMLSelectElement).value)"
>
<option value="nested" selected>중첩된 응답 (기본)</option>
<option value="flat">평평한 목록</option>
<option value="embedded">페이지에 심은 JSON</option>
<option value="failure">실패 응답</option>
</select>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
hired: Date;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'hired',
title: '입사일',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: '월급(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// 서버마다 같은 데이터를 다른 모양으로 보내요: 이름이 중첩되고 값이 글자인 응답, 평평한 목록,
// 페이지 안에 JSON으로 심어 둔 데이터(일부러 망가뜨린 줄 두 개 포함), 그리고 실패 응답이에요.
const RESPONSES: Record<string, unknown> = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: '김민준',
dept: { code: 'D10', name: '개발팀' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: '이서연',
dept: { code: 'D20', name: '디자인팀' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: '박지호', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: '최유나', dept: '영업팀', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: '정도윤', dept: '인사팀', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: '한소희', dept: '개발팀', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: '오세훈', dept: '영업팀', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: '금액이 글자', dept: '개발팀', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: '없는 날짜', dept: '개발팀', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: L(
'로그인이 만료됐어요. 다시 로그인해 주세요.',
'Your session has expired. Please sign in again.',
),
},
};
// 'YYYY-MM-DD'는 달력 날짜예요. new Date(글자)는 UTC로 읽어서 하루가 밀릴 수 있어서 연·월·일로 만들어요.
function toDate(text: unknown): Date {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value: unknown): number => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// 선택 목록의 기본값('중첩된 응답')을 열자마자 불러와서, 표가 비어 있지 않게 해요.
load(api, 'nested');
return () => {};
}
/** 응답 모양이 달라도 같은 Row 목록으로 바꿔요. 값이 없거나 망가진 필드는 예외가 아니라 빈 값이 돼요. */
function mapResponse(body: unknown, kind: string): Row[] {
skipped = 0;
const record = body as { code?: string; message?: string; data?: { items?: unknown[] } };
if (Array.isArray(body)) {
const rows: Row[] = [];
for (const item of body as Record<string, unknown>[]) {
const date = toDate(item['hired']);
// 직접 심어 둔 JSON은 한 줄씩 검사해서 통과한 줄만 넣어요.
if (
kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))
) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK') throw new Error(record.message ?? '요청이 실패했어요');
return (record.data?.items ?? []).map((item) => {
const r = item as Record<string, unknown>;
const dept = r['dept'] as { name?: string } | null;
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api: GridApi<Row>, kind: string): void {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say({
ko: `${rows.length}행을 넣었어요` + (skipped ? ` (망가진 ${skipped}줄은 건너뛰었어요)` : ''),
en: `Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''),
});
} catch (error) {
// 빈 표만 보여 주지 않고, 서버가 준 메시지를 빈 목록 문구로 보여 줘요.
api.setRows([]);
const message = error instanceof Error ? error.message : '오류';
api.setOptions({ messages: { noRows: message } });
say({ ko: `실패: ${message}`, en: `Failed: ${message}` });
}
}
export const actions = {
load: (api: GridApi<Row>, value?: string) => load(api, value ?? 'nested'),
};버튼을 누르면 이 예제의 코드가 StackBlitz나 CodeSandbox로 전송돼요. 누르기 전에는 아무것도 보내지 않아요.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="응답 모양"
[disabled]="!api"
(change)="api && actions.load(api, $any($event.target).value)"
>
<option value="nested" selected>중첩된 응답 (기본)</option>
<option value="flat">평평한 목록</option>
<option value="embedded">페이지에 심은 JSON</option>
<option value="failure">실패 응답</option>
</select>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
// 예제 틀이 알려 주는 페이지 언어(ko/en)에 맞는 문구를 골라요.
const L = (ko: string, en: string): string =>
document.documentElement.dataset.lang === 'en' ? en : ko;
export type LogText = string | { ko: string; en: string };
export interface Row {
id: number;
name: string;
dept: string;
hired: Date;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: '이름', width: 130 },
{ id: 'dept', title: '부서', width: 120 },
{
id: 'hired',
title: '입사일',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: '월급(원)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('ko-KR'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// 서버마다 같은 데이터를 다른 모양으로 보내요: 이름이 중첩되고 값이 글자인 응답, 평평한 목록,
// 페이지 안에 JSON으로 심어 둔 데이터(일부러 망가뜨린 줄 두 개 포함), 그리고 실패 응답이에요.
const RESPONSES: Record<string, unknown> = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: '김민준',
dept: { code: 'D10', name: '개발팀' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: '이서연',
dept: { code: 'D20', name: '디자인팀' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: '박지호', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: '최유나', dept: '영업팀', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: '정도윤', dept: '인사팀', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: '한소희', dept: '개발팀', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: '오세훈', dept: '영업팀', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: '금액이 글자', dept: '개발팀', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: '없는 날짜', dept: '개발팀', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: L(
'로그인이 만료됐어요. 다시 로그인해 주세요.',
'Your session has expired. Please sign in again.',
),
},
};
// 'YYYY-MM-DD'는 달력 날짜예요. new Date(글자)는 UTC로 읽어서 하루가 밀릴 수 있어서 연·월·일로 만들어요.
function toDate(text: unknown): Date {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value: unknown): number => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// 선택 목록의 기본값('중첩된 응답')을 열자마자 불러와서, 표가 비어 있지 않게 해요.
load(api, 'nested');
return () => {};
}
/** 응답 모양이 달라도 같은 Row 목록으로 바꿔요. 값이 없거나 망가진 필드는 예외가 아니라 빈 값이 돼요. */
function mapResponse(body: unknown, kind: string): Row[] {
skipped = 0;
const record = body as { code?: string; message?: string; data?: { items?: unknown[] } };
if (Array.isArray(body)) {
const rows: Row[] = [];
for (const item of body as Record<string, unknown>[]) {
const date = toDate(item['hired']);
// 직접 심어 둔 JSON은 한 줄씩 검사해서 통과한 줄만 넣어요.
if (
kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))
) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK') throw new Error(record.message ?? '요청이 실패했어요');
return (record.data?.items ?? []).map((item) => {
const r = item as Record<string, unknown>;
const dept = r['dept'] as { name?: string } | null;
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api: GridApi<Row>, kind: string): void {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say({
ko: `${rows.length}행을 넣었어요` + (skipped ? ` (망가진 ${skipped}줄은 건너뛰었어요)` : ''),
en: `Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''),
});
} catch (error) {
// 빈 표만 보여 주지 않고, 서버가 준 메시지를 빈 목록 문구로 보여 줘요.
api.setRows([]);
const message = error instanceof Error ? error.message : '오류';
api.setOptions({ messages: { noRows: message } });
say({ ko: `실패: ${message}`, en: `Failed: ${message}` });
}
}
export const actions = {
load: (api: GridApi<Row>, value?: string) => load(api, value ?? 'nested'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<div id="app">
<div class="toolbar">
<select aria-label="Response shape" id="load">
<option value="nested" selected>Nested (default)</option>
<option value="flat">Flat list</option>
<option value="embedded">Embedded JSON</option>
<option value="failure">Failure</option>
</select>
</div>
<div id="grid" style="height: 300px"></div>
</div>
<script type="module" src="./main.js"></script>import { createGrid } from 'maxgrid';
import { actions, options, setup } from './example';
const api = createGrid(document.getElementById('grid'), options);
setup(api, console.log);
document.getElementById('load').addEventListener('change', (event) => actions.load(api, event.target.value));export const options = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'hired',
title: 'Hire date',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// Each server sends the same data in a different shape: a response with nested names and string values, a flat list,
// data embedded in the page as JSON (including two lines broken on purpose), and a failure response.
const RESPONSES = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: 'Liam Carter',
dept: { code: 'D10', name: 'Dev' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: 'Emma Stone',
dept: { code: 'D20', name: 'Design' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: 'Noah Reed', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: 'Olivia Hayes', dept: 'Sales', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: 'Ethan Brooks', dept: 'HR', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: 'Sophia Bell', dept: 'Dev', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: 'Mason Gray', dept: 'Sales', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: 'Amount is text', dept: 'Dev', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: 'Invalid date', dept: 'Dev', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: 'Your session has expired. Please sign in again.',
},
};
// 'YYYY-MM-DD' is a calendar date. new Date(text) reads it as UTC and can shift it by a day, so build it from year, month and day.
function toDate(text) {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value) => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say = () => { };
export function setup(api, log) {
say = log;
// Load the select's default ('nested response') as soon as it opens, so the table is not empty.
load(api, 'nested');
return () => { };
}
/** Turns different response shapes into the same Row list. A missing or broken field becomes an empty value, not an exception. */
function mapResponse(body, kind) {
skipped = 0;
const record = body;
if (Array.isArray(body)) {
const rows = [];
for (const item of body) {
const date = toDate(item['hired']);
// JSON embedded by hand is checked line by line, and only lines that pass are put in.
if (kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK')
throw new Error(record.message ?? 'The request failed');
return (record.data?.items ?? []).map((item) => {
const r = item;
const dept = r['dept'];
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api, kind) {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say(`Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''));
}
catch (error) {
// Instead of showing only an empty table, show the message the server sent as the empty-list text.
api.setRows([]);
const message = error instanceof Error ? error.message : 'Error';
api.setOptions({ messages: { noRows: message } });
say(`Failed: ${message}`);
}
}
export const actions = {
load: (api, value) => load(api, value ?? 'nested'),
};<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Map a server response to grid rows</title>
</head>
<body>
<div class="toolbar">
<select aria-label="Response shape" id="load">
<option value="nested" selected>Nested (default)</option>
<option value="flat">Flat list</option>
<option value="embedded">Embedded JSON</option>
<option value="failure">Failure</option>
</select>
</div>
<div id="grid" style="height: 300px"></div>
<ul id="log" aria-live="polite"></ul>
<script src="https://cdn.maxmine.com/maxgrid/latest/maxgrid.min.js"></script>
<script>
const options = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'hired',
title: 'Hire date',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// Each server sends the same data in a different shape: a response with nested names and string values, a flat list,
// data embedded in the page as JSON (including two lines broken on purpose), and a failure response.
const RESPONSES = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: 'Liam Carter',
dept: { code: 'D10', name: 'Dev' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: 'Emma Stone',
dept: { code: 'D20', name: 'Design' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: 'Noah Reed', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: 'Olivia Hayes', dept: 'Sales', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: 'Ethan Brooks', dept: 'HR', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: 'Sophia Bell', dept: 'Dev', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: 'Mason Gray', dept: 'Sales', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: 'Amount is text', dept: 'Dev', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: 'Invalid date', dept: 'Dev', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: 'Your session has expired. Please sign in again.',
},
};
// 'YYYY-MM-DD' is a calendar date. new Date(text) reads it as UTC and can shift it by a day, so build it from year, month and day.
function toDate(text) {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value) => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say = () => { };
function setup(api, log) {
say = log;
// Load the select's default ('nested response') as soon as it opens, so the table is not empty.
load(api, 'nested');
return () => { };
}
/** Turns different response shapes into the same Row list. A missing or broken field becomes an empty value, not an exception. */
function mapResponse(body, kind) {
skipped = 0;
const record = body;
if (Array.isArray(body)) {
const rows = [];
for (const item of body) {
const date = toDate(item['hired']);
// JSON embedded by hand is checked line by line, and only lines that pass are put in.
if (kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK')
throw new Error(record.message ?? 'The request failed');
return (record.data?.items ?? []).map((item) => {
const r = item;
const dept = r['dept'];
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api, kind) {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say(`Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''));
}
catch (error) {
// Instead of showing only an empty table, show the message the server sent as the empty-list text.
api.setRows([]);
const message = error instanceof Error ? error.message : 'Error';
api.setOptions({ messages: { noRows: message } });
say(`Failed: ${message}`);
}
}
const actions = {
load: (api, value) => load(api, value ?? 'nested'),
};
options.ariaLabel = "Map a server response to grid rows";
const api = MaxGrid.createGrid(document.getElementById('grid'), options);
setup(api, (message) => {
const item = document.createElement('li');
item.textContent =
typeof message === 'string' ? message : navigator.language.startsWith('ko') ? message.ko : message.en;
document.getElementById('log').prepend(item);
});
document.getElementById('load').addEventListener('change', (event) => actions.load(api, event.target.value));
</script>
</body>
</html>When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { useEffect } from 'react';
import { Grid, useGridApi } from '@maxgrid/react';
import { actions, options, setup, type Row } from './example';
export function ExampleGrid() {
const [api, gridRef] = useGridApi<Row>();
useEffect(() => (api ? setup(api, console.log) : undefined), [api]);
return (
<>
<div className="toolbar">
<select
aria-label="Response shape"
disabled={!api}
onChange={(event) => api && actions.load(api, event.target.value)}
>
<option value="nested">Nested (default)</option>
<option value="flat">Flat list</option>
<option value="embedded">Embedded JSON</option>
<option value="failure">Failure</option>
</select>
</div>
<Grid style={{ height: 300 }} ref={gridRef} options={options} />
</>
);
}import type { GridApi, GridOptions } from '@maxgrid/react';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
hired: Date;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'hired',
title: 'Hire date',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// Each server sends the same data in a different shape: a response with nested names and string values, a flat list,
// data embedded in the page as JSON (including two lines broken on purpose), and a failure response.
const RESPONSES: Record<string, unknown> = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: 'Liam Carter',
dept: { code: 'D10', name: 'Dev' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: 'Emma Stone',
dept: { code: 'D20', name: 'Design' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: 'Noah Reed', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: 'Olivia Hayes', dept: 'Sales', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: 'Ethan Brooks', dept: 'HR', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: 'Sophia Bell', dept: 'Dev', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: 'Mason Gray', dept: 'Sales', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: 'Amount is text', dept: 'Dev', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: 'Invalid date', dept: 'Dev', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: 'Your session has expired. Please sign in again.',
},
};
// 'YYYY-MM-DD' is a calendar date. new Date(text) reads it as UTC and can shift it by a day, so build it from year, month and day.
function toDate(text: unknown): Date {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value: unknown): number => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// Load the select's default ('nested response') as soon as it opens, so the table is not empty.
load(api, 'nested');
return () => {};
}
/** Turns different response shapes into the same Row list. A missing or broken field becomes an empty value, not an exception. */
function mapResponse(body: unknown, kind: string): Row[] {
skipped = 0;
const record = body as { code?: string; message?: string; data?: { items?: unknown[] } };
if (Array.isArray(body)) {
const rows: Row[] = [];
for (const item of body as Record<string, unknown>[]) {
const date = toDate(item['hired']);
// JSON embedded by hand is checked line by line, and only lines that pass are put in.
if (
kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))
) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK') throw new Error(record.message ?? 'The request failed');
return (record.data?.items ?? []).map((item) => {
const r = item as Record<string, unknown>;
const dept = r['dept'] as { name?: string } | null;
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api: GridApi<Row>, kind: string): void {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say(`Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''));
} catch (error) {
// Instead of showing only an empty table, show the message the server sent as the empty-list text.
api.setRows([]);
const message = error instanceof Error ? error.message : 'Error';
api.setOptions({ messages: { noRows: message } });
say(`Failed: ${message}`);
}
}
export const actions = {
load: (api: GridApi<Row>, value?: string) => load(api, value ?? 'nested'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
<script setup lang="ts">
import { onBeforeUnmount, shallowRef } from 'vue';
import { Grid, type GridApi } from '@maxgrid/vue';
import { actions, options, setup, type Row } from './example';
const api = shallowRef<GridApi<Row> | null>(null);
let stop: (() => void) | undefined;
function onReady(event: { api: GridApi<Row> }) {
api.value = event.api;
stop = setup(event.api, console.log);
}
onBeforeUnmount(() => stop?.());
</script>
<template>
<div class="toolbar">
<select
aria-label="Response shape"
:disabled="!api"
@change="api && actions.load(api, ($event.target as HTMLSelectElement).value)"
>
<option value="nested" selected>Nested (default)</option>
<option value="flat">Flat list</option>
<option value="embedded">Embedded JSON</option>
<option value="failure">Failure</option>
</select>
</div>
<Grid style="height: 300px" :options="options" @ready="onReady" />
</template>import type { GridApi, GridOptions } from '@maxgrid/vue';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
hired: Date;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'hired',
title: 'Hire date',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// Each server sends the same data in a different shape: a response with nested names and string values, a flat list,
// data embedded in the page as JSON (including two lines broken on purpose), and a failure response.
const RESPONSES: Record<string, unknown> = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: 'Liam Carter',
dept: { code: 'D10', name: 'Dev' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: 'Emma Stone',
dept: { code: 'D20', name: 'Design' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: 'Noah Reed', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: 'Olivia Hayes', dept: 'Sales', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: 'Ethan Brooks', dept: 'HR', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: 'Sophia Bell', dept: 'Dev', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: 'Mason Gray', dept: 'Sales', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: 'Amount is text', dept: 'Dev', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: 'Invalid date', dept: 'Dev', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: 'Your session has expired. Please sign in again.',
},
};
// 'YYYY-MM-DD' is a calendar date. new Date(text) reads it as UTC and can shift it by a day, so build it from year, month and day.
function toDate(text: unknown): Date {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value: unknown): number => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// Load the select's default ('nested response') as soon as it opens, so the table is not empty.
load(api, 'nested');
return () => {};
}
/** Turns different response shapes into the same Row list. A missing or broken field becomes an empty value, not an exception. */
function mapResponse(body: unknown, kind: string): Row[] {
skipped = 0;
const record = body as { code?: string; message?: string; data?: { items?: unknown[] } };
if (Array.isArray(body)) {
const rows: Row[] = [];
for (const item of body as Record<string, unknown>[]) {
const date = toDate(item['hired']);
// JSON embedded by hand is checked line by line, and only lines that pass are put in.
if (
kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))
) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK') throw new Error(record.message ?? 'The request failed');
return (record.data?.items ?? []).map((item) => {
const r = item as Record<string, unknown>;
const dept = r['dept'] as { name?: string } | null;
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api: GridApi<Row>, kind: string): void {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say(`Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''));
} catch (error) {
// Instead of showing only an empty table, show the message the server sent as the empty-list text.
api.setRows([]);
const message = error instanceof Error ? error.message : 'Error';
api.setOptions({ messages: { noRows: message } });
say(`Failed: ${message}`);
}
}
export const actions = {
load: (api: GridApi<Row>, value?: string) => load(api, value ?? 'nested'),
};When you click, the example code is sent to StackBlitz or CodeSandbox. Nothing is sent before you click.
import { Component, OnDestroy } from '@angular/core';
import { GridComponent, isGridEvent, type GridApi, type GridEventMessage } from '@maxgrid/angular';
import { actions, options, setup, type Row } from './example';
@Component({
selector: 'app-example-grid',
standalone: true,
imports: [GridComponent],
template: `
<div class="toolbar">
<select
aria-label="Response shape"
[disabled]="!api"
(change)="api && actions.load(api, $any($event.target).value)"
>
<option value="nested" selected>Nested (default)</option>
<option value="flat">Flat list</option>
<option value="embedded">Embedded JSON</option>
<option value="failure">Failure</option>
</select>
</div>
<mx-grid style="height: 300px" [options]="options" [events]="relayed" (gridEvent)="onEvent($event)" />
`,
})
export class ExampleGridComponent implements OnDestroy {
readonly options = options;
readonly actions = actions;
readonly relayed = ['ready'] as const;
api: GridApi<Row> | null = null;
private stop: (() => void) | null = null;
onEvent(event: GridEventMessage<Row>): void {
if (isGridEvent(event, 'ready')) {
this.api = event.payload.api;
this.stop = setup(this.api, console.log);
}
}
ngOnDestroy(): void {
this.stop?.();
}
}import type { GridApi, GridOptions } from '@maxgrid/angular';
export type LogText = string;
export interface Row {
id: number;
name: string;
dept: string;
hired: Date;
salary: number;
}
export const options: GridOptions<Row> = {
columns: [
{ id: 'name', title: 'Name', width: 130 },
{ id: 'dept', title: 'Department', width: 120 },
{
id: 'hired',
title: 'Hire date',
kind: 'date',
width: 130,
formatValue: (v) => (v instanceof Date && !Number.isNaN(v.getTime()) ? ymd(v) : ''),
},
{
id: 'salary',
title: 'Salary ($)',
kind: 'number',
width: 130,
align: 'end',
formatValue: (value) => Number(value).toLocaleString('en-US'),
},
],
rows: [],
rowKey: 'id',
};
const ymd = (d: Date): string =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
// Each server sends the same data in a different shape: a response with nested names and string values, a flat list,
// data embedded in the page as JSON (including two lines broken on purpose), and a failure response.
const RESPONSES: Record<string, unknown> = {
nested: {
code: 'OK',
data: {
items: [
{
emp_no: 101,
emp_nm: 'Liam Carter',
dept: { code: 'D10', name: 'Dev' },
hire_dt: '2021-03-15',
pay: '4200000.00',
},
{
emp_no: 102,
emp_nm: 'Emma Stone',
dept: { code: 'D20', name: 'Design' },
hire_dt: '2022-07-01',
pay: '3800000.00',
},
{ emp_no: 103, emp_nm: 'Noah Reed', dept: null, hire_dt: '', pay: 'n/a' },
],
},
},
flat: [
{ id: 1, name: 'Olivia Hayes', dept: 'Sales', hired: '2020-01-10', salary: 4500000 },
{ id: 2, name: 'Ethan Brooks', dept: 'HR', hired: '2019-09-02', salary: 3900000 },
],
embedded: [
{ id: 1, name: 'Sophia Bell', dept: 'Dev', hired: '2026-10-28', salary: 4100000 },
{ id: 2, name: 'Mason Gray', dept: 'Sales', hired: '2026-10-30', salary: 3700000 },
{ id: 3, name: 'Amount is text', dept: 'Dev', hired: '2026-11-02', salary: 'n/a' },
{ id: 4, name: 'Invalid date', dept: 'Dev', hired: '2026-13-40', salary: 1000 },
],
failure: {
code: 'ERR_AUTH',
message: 'Your session has expired. Please sign in again.',
},
};
// 'YYYY-MM-DD' is a calendar date. new Date(text) reads it as UTC and can shift it by a day, so build it from year, month and day.
function toDate(text: unknown): Date {
const [y, m, d] = String(text).split('-').map(Number);
const date = y && m && d ? new Date(y, m - 1, d) : new Date(NaN);
return date.getMonth() === (m ?? 0) - 1 ? date : new Date(NaN);
}
const toNumber = (value: unknown): number => {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
};
let skipped = 0;
let say: (message: LogText) => void = () => {};
export function setup(api: GridApi<Row>, log: (message: LogText) => void) {
say = log;
// Load the select's default ('nested response') as soon as it opens, so the table is not empty.
load(api, 'nested');
return () => {};
}
/** Turns different response shapes into the same Row list. A missing or broken field becomes an empty value, not an exception. */
function mapResponse(body: unknown, kind: string): Row[] {
skipped = 0;
const record = body as { code?: string; message?: string; data?: { items?: unknown[] } };
if (Array.isArray(body)) {
const rows: Row[] = [];
for (const item of body as Record<string, unknown>[]) {
const date = toDate(item['hired']);
// JSON embedded by hand is checked line by line, and only lines that pass are put in.
if (
kind === 'embedded' &&
(typeof item['salary'] !== 'number' || Number.isNaN(date.getTime()))
) {
skipped += 1;
continue;
}
rows.push({
id: toNumber(item['id']),
name: String(item['name'] ?? ''),
dept: String(item['dept'] ?? ''),
hired: date,
salary: toNumber(item['salary']),
});
}
return rows;
}
if (record.code !== 'OK') throw new Error(record.message ?? 'The request failed');
return (record.data?.items ?? []).map((item) => {
const r = item as Record<string, unknown>;
const dept = r['dept'] as { name?: string } | null;
return {
id: toNumber(r['emp_no']),
name: String(r['emp_nm'] ?? ''),
dept: String(dept?.name ?? ''),
hired: toDate(r['hire_dt']),
salary: toNumber(r['pay']),
};
});
}
function load(api: GridApi<Row>, kind: string): void {
try {
api.setOptions({ messages: {} });
const rows = mapResponse(RESPONSES[kind], kind);
api.setRows(rows);
say(`Put in ${rows.length} rows` + (skipped ? ` (skipped ${skipped} broken lines)` : ''));
} catch (error) {
// Instead of showing only an empty table, show the message the server sent as the empty-list text.
api.setRows([]);
const message = error instanceof Error ? error.message : 'Error';
api.setOptions({ messages: { noRows: message } });
say(`Failed: ${message}`);
}
}
export const actions = {
load: (api: GridApi<Row>, value?: string) => load(api, value ?? 'nested'),
};