이 페이지의 내용
문서기능 가이드
기능 가이드02

서비스 객체 주입

설정과 비즈니스 로직을 서비스 객체로 모아 재사용합니다.

한국어 문서약 24분

서비스 객체 구성#

서비스 객체를 주입하여 모델(BindModel) 객체를 간편하게 생성할 수 있습니다.

서비스 객체는 다음과 같은 영역으로 구성됩니다:

  • 기본 영역
    • 기본 서버 설정, 공통 콜백 함수, 이벤트, 테이블 설정을 정의합니다.
  • 아이템 영역
    • 모델(BindModel)에서 공통 컬럼 속성을 관리합니다.
  • 명령 영역
    • 명령(BindCommand)을 정의하고, 실행 흐름과 관련된 설정을 구성합니다.
  • 매핑 영역
    • 아이템을 테이블이나 명령의 뷰(MetaView)와 매핑하여 데이터 흐름을 제어합니다.
  • 함수 영역
    • 사용자 정의 함수로 비즈니스 로직을 캡슐화하여 외부에서 쉽게 호출할 수 있도록 구성합니다.
  • 전처리 영역
    • 모델 init() 초기화 시 호출되는 전처리 함수로 초기 설정 및 유효성 검사 등의 작업을 처리합니다.

기본 영역#

기본 영역에는 기본서버설정, 기본 콜백함수, 전역 이벤트, 테이블 확장을 구성합니다.

ts
type ServiceType = {
    // 기본 서버 설정
    url?: string,

    // 기본 axios config
    baseConfig?: axiosConfig,
    
    // 추가할 테이블
    tables?: string[],
    
    // 기본 콜백 함수
    cbBaseBegin?: (model: BindModel, cmd: BindCommand) => void;
    cbBaseValid?: (view: MetaView, cmd: BindCommand, model: BindModel) => boolean,
    cbBaseBind?: (view: MetaView, cmd: BindCommand, cfg: object) => void,
    cbBaseResult?: (data: object, cmd: BindCommand, res: object) => object,
    cbBaseOutput?: (outs: MetaViewCollection, cmd: BindCommand, res: object) => void,
    cbBaseEnd?: (status: number, cmd: BindCommand, res: object) => void,
    
    // 공통 이벤트
    onExecute?: (bm: BindModel, bc: BindCommand) => void,
    onExecuted?: (bm: BindModel, bc: BindCommand) => void,
};

URL 설정#

url 속성은 서버 요청에 사용되는 기본 경로입니다.

js
const bm = new BindModel({
	url: '/user'
});

Tip url 속성은 baseConfig.url 의 참조합니다.

baseConfig 설정#

axios 모듈의 config 설정을 구성하는 기본 객체를 지정합니다.

명령(BindCommand)에서 config를 따로 설정하지 않으면, baseConfig 값이 사용됩니다.

js
const bm = new BindModel({
	baseConfig: {
		method: 'post',
		url: '/user',
		baseUrl: 'https://bindmodel.com',
		responseType: 'json',
		headers: {'X-Requested-With': 'XMLHttpRequest'},
		timeout: 1000, // 기본값은 `0` (타임아웃 없음)
		auth: { username: 'janedoe', password: 's00pers3cret' },
		// ... 기타 axios 설정 참조
	}
});
  • baseConfig.url 속성은 url 속성과 동일한 값을 참조합니다.

참조 : axios > 요청 Config

기본 콜백함수 설정#

기본 콜백 함수는 모든 명령(BindCommand)에 적용됩니다.

명령에 특정 콜백 함수가 없을 경우, 해당 기본 콜백 함수가 호출됩니다.

js
const bm = new BindModel({
    cbBaseBegin: function(model, cmd) { 
        console.log('기본 시작 콜백'); 
    },
    cbBaseValid: function(view, cmd, model) {
        console.log('기본 유효성 검사 콜백');
        return true;
    },
    cbBaseBind: function(view, cmd, cfg) { 
        console.log('기본 서버 요청 콜백'); 
    },
    cbBaseResult: function(data, cmd, res) {
        console.log('기본 서버 응답 콜백');
        return data;
    },
    cbBaseOutput: function(view, cmd, res) { 
        console.log('기본 응답 출력 콜백'); 
    },
    cbBaseEnd: function(status, cmd, res) { 
        console.log('기본 종료 콜백'); 
    }
});

참조 : 흐름 제어

모델 이벤트 설정#

모델(BindModel)의 execute() 호출 시 발생하는 이벤트를 처리합니다.

js
const bm = new BindModel({
    onExecute: function(bModel, bCommand) { 
        console.log('실행 시작 이벤트'); 
    },
    onExecuted: function(bModel, bCommand) { 
        console.log('실행 종료 이벤트');
    }
});

Tip 이벤트는 여러 개를 등록할 수 있으며, 콜백 함수는 하나만 설정 가능합니다.

참조 : 이벤트 설정 > 모델 실행 이벤트, 흐름 제어

아이템 영역#

아이템 영역은 컬럼의 공통 속성값을 정의하는데 사용됩니다.

Tip 서비스 객체를 주입하면 BindModel의 items 컬렉션에 키-값 형식으로 등록됩니다. 이후, 이 컬렉션은 컬럼 등록 및 매핑에 활용됩니다.

참조 : 공통 컬럼 속성

ts
type KeyType = 'none' | 'value' | 'text' | 'html' | 'prop' | 'attr' | 'css';
type ValType = string | number | boolean;
type RegExpType = { reg: RegExp, msg: string, match?: boolean };
type FuncType = (value: any) => boolean;
type ConstraintType = RegExpType | FuncType;
type ColumnType = {
    columnName?: string,
    selector?: { key: string, type: KeyType },
    getter?: () => any,
    setter?: (val: any) => any,
    getFilter?: () => any,
    setFilter?: (val: any) => any,
    default?: string | number | boolean | null,
    value?: ValType,
    alias?: string,
    caption?: string,
    constraints?: ConstraintType | ConstraintType[],
    required?: boolean | false,
};

type serviceType = {
    items?: { [key: string]: ColumnType | ValType }
};
  • 컬럼 등록 시, items의 속성값이 기본형(string, number, boolean)이면 초기값으로 설정되며, 객체일 경우 해당 객체가 컬럼 설정값으로 사용됩니다.

이 예제는 아이템 영역을 설정하는 방법과 다양한 속성값을 활용하여 컬럼 속성을 정의하는 데 유용합니다. 이를 통해 컬럼의 기본값, 제약 조건, 셀렉터, getter/setter 등을 효율적으로 관리할 수 있습니다.

js
const bm = new BindModel({
    // 아이템
    items: {
        aa: 'Cat',    // 기본값이 'Cat'인 컬럼
		bb: 10,       // 기본값이 10 인 컬럼
        cc: true,     // 기본값이 true 인 컬럼
        dd: {
            selector: { key: '#U_ID', type: 'value' },  // 셀렉터 설정
            setter: (val) => { /*외부에 설정 영역*/ },      // setter 설정
            getter: () => { return '외부값'; },           // getter 설정
        },
        ee: {
            required: true,                             // 필수 값 설정
            setFilter: (val) => { /*외부에 설정영역*/ },    // 값 설정 필터
            getFilter: () => { return '외부값'; },        // 값 가져오기 필터
        },
        ff: {
            constraints: { reg: /abc/, msg: '매칭 실패!' } // 제약조건 설정
        }
    }
});

명령 영역#

명령(BindCommand) 객체를 구성합니다.

ts
type OptionType = 'SEND' | 'VIEW' | 'ALL' | 'PICK'; // default 'SEND'
type SchemaType = 'AUTO' | 'DATA' | 'ENTITY';       // default 'AUTO'
type IndexType = number | number[]; // // default 0
type OutOptType = { option: OptionType, schema: SchemaType, index: IndexType }
type CmdPropType = {
    outputOption?: OutOptType | OptionType | SchemaType | IndexType,
	views?: string[],              // 추가할 뷰(MetaView) 목록
    config?: object,               // axios 설정 객체
    url?: string,                  // 서버 요청 URL
    // 명령 콜백 함수
    cbBegin?: (model: BindModel, cmd: BindCommand) => void,
    cbValid?: (view: MetaView, cmd: BindCommand, model: BindModel) => boolean,
    cbBind?: (view: MetaView, cmd: BindCommand, cfg: object) => void,
    cbResult?: (data: object, cmd: BindCommand, res: object) => object,
    cbOutput?: (views: MetaViewCollection, cmd: BindCommand, res: object) => void,
    cbEnd?: (status: number, cmd: BindCommand, res: object) => void,
    // 명령 이벤트
    onExecute?: (model: BindModel, cmd: BindCommand) => void,
    onExecuted?: (model: BindModel, cmd: BindCommand) => void,
};
type CommandType = { [key: string]: CmdPropType | {} };

type ServiceType = {
    command?: CommandType;
};

서비스 객체를 주입하면 모델(BindModel)의 command 컬렉션에 키와 명령(BindCommand) 객체가 등록됩니다.

js
const bm = new BindModel({
    command: {
        create: {},
        read: {
            outputOption: 'VIEW',       // 데이터를 컬럼값에 설정 (지정된 컬럼)
            config: { method: 'GET' },  // GET 요청 설정
            cbEnd: function() {         // 처리 완료 후 콜백 함수
	            alert('정상처리되었습니다.'); 
			} 
        },
        update: {
            views: ['two'],  // 'two' 뷰를 추가
            url: '/user'     // 요청할 URL 경로
        }
    }
});

// bm.cmd['create'] : BindCommand
// bm.cmd['read']   : BindCommand
// bm.cmd['update'] : BindCommand

참조 : 명령 구성

outputOption 설정#

서버 응답 데이터를 처리하는 방식 지정

  • SEND : 출력하지 않음 (기본값)
  • VIEW : 정의된 컬럼 데이터 + 특정 인덱스 데이터를 컬럼값으로 설정
  • ALL : 모든 데이터를 가져옴
  • PICK : 정의된 컬럼과 매칭되는 데이터만 가져옴

서버 응답 데이터 형식 지정

  • AUTO : JSON 데이터 검사 후 엔티티로 변환
  • DATA : JSON 데이터를 rows 속성에 강제 변환
  • ENTITY : JSON 데이터를 엔티티 형식의 데이터로 취급

참조 : 명령 구성 > 출력 옵션의 종류, JSON 스키마 가이드

views 설정#

명령에 추가로 사용할 출력 뷰(MetaView)를 정의

js
update: {
    views: ['customView']
}

config 설정#

axios 요청 설정:

js
({
read: {
    config: { method: 'POST', timeout: 1000 }
}
});

참조 : axios > 요청 Config

명령 콜백 함수 설정#

명령의 특정 단계에서 동작을 정의:

js
({
read: {
    cbEnd: function(cmd) {
        console.log(`명령 '${cmd.name}' 실행 완료`);
    }
}
});

참조 : 흐름 제어

매핑 영역#

아이템에 등록된 컬럼 속성을 지정한 명령(BindCommand)의 선택된 뷰(MetaView)에 매핑합니다.

ts
type CommandName = '$all' | string;  // 명령 이름 ('$all'은 모든 명령을 의미)
type ViewName = 'valid' | 'bind' | 'output' | '$all' | string; // 뷰 이름
type MappingType = {
    [key: ColumnName]: {
        [key: CommandName]: ViewName | ViewName[] // 명령 이름과 매핑된 뷰 목록
    }
};

type ServiceType = {
    mapping?: MappingType
};

Tip

아이템 이름 규칙 : [테이블명 . ]컬럼명 매핑시 아이템명은 [테이블명.]아이템명 형식으로 지정할 수 있습니다.

매핑할 컬럼명과 동일한 이름의 아이템이 존재할 경우 아이템의 속성을 사용하여 컬럼을 등록합니다.

테이블명이 생략되면 기본 테이블(_baseTable == first)에 컬럼이 추가되며, 지정된 테이블이 존재하지 않으면 자동으로 생성됩니다.

지정한 명령에 개별적으로 매핑할 수 있습니다. 특정 명령(BindCommand)이 존재하지 않으면 자동으로 생성됩니다.

Tip

매핑 가능한 뷰는 기본 제공되는 valid, bind, output, misc에 한정됩니다. 이 외의 출력 뷰에 매핑하려면, 먼저 해당 뷰를 사전에 추가해야 합니다.

js
const bm = new BindModel({
    mapping: {
        'aa': { $all: ['valid'] },        // 모든 명령의 'valid' 뷰에 'aa' 등록
        'bb': { cmd1: ['bind'] },          // 'cmd1' 명령의 'bind' 뷰에 'bb' 등록
        'second.cc': { cmd2: ['output'] }  // 'cmd2' 명령의 'output' 뷰에 'cc' 등록
    }
});

// bm.items.count == 4 ('aa','bb','cc','dd')
// bm.first.columns.count == 2 ('aa','bb')
// bm.second.columns.count == 1 ('cc')

// bm.cmd['cmd1'].valid.columns.count == 1 ('aa')
// bm.cmd['cmd1'].bind.columns.count == 1 ('bb')
// bm.cmd['cmd1'].output.columns.count == 0

// bm.cmd['cmd2'].valid.columns.count == 1 ('aa')
// bm.cmd['cmd2'].bind.columns.count == 0
// bm.cmd['cmd2'].output.columns.count  == 1 ('cc')

Tip

객체 생성 후에는 setMapping() 메서드를 사용하여 매핑을 설정할 수 있습니다.

'$all' : 전체 매핑#

모든 명령(BindCommand)을 대상으로 매핑합니다.

js
aa: { $all: ['valid'] }

모든 뷰(valid, bind, output, misc)를 대상으로 매핑합니다.

js
aa: { cmd1: '$all' }

명령에 기본 뷰 외의 추가 뷰가 포함되어 있을 경우, 해당 뷰는 '$all' 옵션의 매핑 대상에 포함됩니다.

명시적 테이블명 지정#

특정 테이블 컬럼을 명시적으로 매핑:

js
({
'second.cc': { cmd2: ['output'] }
});
  • 'second' 테이블의 'cc' 컬럼이 'cmd2' 명령의 'output' 뷰에 매핑됩니다.

함수 영역#

모델(BindModel)의 fn 속성 컬렉션은 사용자 정의 함수를 등록하고 활용할 수 있는 영역입니다.

이 영역을 사용하면 반복적인 작업을 캡슐화하거나, 콜백 함수와 연계하여 효과적으로 로직을 실행할 수 있습니다.

ts
type fnType = { [key: string]: Function };

type ServiceType = {
    fn?: fnType
};

fn 속성에 사용자 함수를 정의하고, 모델 내부 및 외부에서 호출할 수 있습니다.

js
const bm = new BindModel({
    // 기본 시작 콜백에서 사용자 함수 호출
    cbBaseBegin: function(model, cmd) {
		model.fn.execCreate();        // 명령(model)에서 접근
        this.bindModel.fn.sum(1, 1);  // 모델(this.bindModel) 객체에서 접근
    },
    // 명령 종료 시 사용자 함수 호출
    command: {
        create: {
            cbEnd: function() {
                this.bindModel.fn.sum(1, 2);
            }
        },
    },
    // 사용자 함수 정의
    fn: {
        sum: function(a, b) {return a + b},
        execCreate: function() {
            this.bindModel.command['read'].execute();
        }
    }
});
  • 콜백 함수 내에서 this.bindModel은 현재 BindModel 객체를 참조합니다.

외부에서 사용자 함수를 호출할 수 있습니다.

js
var bm = new BindModel();
//....

// 버튼 클릭 이벤트와 사용자 함수 연결
$('#btn_create').click(function() {
    bm.fn.execCreate();
});

함수이름 규칙 함수 이름을 명확하게 정의하여 내부와 외부에서 쉽게 식별할 수 있도록 관리합니다.

Tip 서비스 객체에서 this.bindModel은 항상 현재 모델 객체를 참조하므로, 객체 간의 종속성을 효과적으로 관리할 수 있습니다.

전처리 영역#

모델(BindModel) 객체에서 init()을 호출하면 아래 전처리 함수들이 순차적으로 실행됩니다.

이는 주로 서비스 객체의 유효성 검사 및 초기화에 활용됩니다.

ts
type ServiceType = {
    preRegister?: (bindModel) => void,
    preCheck?: (bindModel) => boolean,
    preReady?: (bindModel) => void
};
  • preRegister() : 전처리 단계에서 가장 먼저 호출되며, 초기화 또는 등록을 구현합니다.
  • preCheck() : 유효성 검사를 수행하며, 검사 성공 시 true를 반환되어야 다음 단계로 진행됩니다.
  • preReady() : preCheck()에서 true를 반환한 경우 호출되며, 최종 준비 완료 로직을 구현합니다.

Tip 전처리 함수에서 첫 번째 인자로 전달되는 bindModel은 현재 모델(BindModel) 객체를 참조합니다.

js
const bm = new BindModel({
    preRegister: function(bindModel) { 
        console.log('1. 전처리: 초기화 또는 등록');
    },
    preCheck: function(bindModel) {
        console.log('2. 전처리: 유효성 검사');
        // Selector 검사 후 성공 여부 반환
        if (bindModel.checkSelector().length === 0) return true;
    },
    preReady: function(bindModel) { 
        console.log('3. 전처리: 준비 완료');
        // 준비 완료 후 특정 명령 실행
        bindModel.command['test'].execute();
    },
});

// DOM이 준비되면 초기화 수행
$(document).ready(function () {
    bm.init();
});
  • init() 호출하면 전처리 함수는 preRegister() >> preCheck() >> preReady() 순차적으로 실행합니다.

서비스 객체 설정#

서비스 객체는 BindModel 생성자 또는 setService() 메서드를 사용하여 주입할 수 있습니다.

생성자로 설정#

모델(BindModel) 객체를 생성할 때, 서비스 객체를 인자로 전달합니다.

ts
declare function BindModel(service?: ServiceType);
js
let service = {
	tables: ['second']
	// etc config ...
};

const bm = new BindModel(service);

// bm.second instanceof MetaTable : true
  • 서비스 객체를 통해 ‘second’ 테이블이 추가되었습니다.

메소드로 설정#

모델(BindModel) 객체를 생성한 후, setService() 메서드를 호출하여 서비스 객체를 주입합니다.

js
let service = {
	tables: ['second']
	// etc config ...
};
const bm = new BindModel();

bm.setService(service);

// bm.second instanceof MetaTable : true

Tip setService() 메서드를 사용하면 서비스 객체를 여러 번 주입할 수 있습니다. 이를 통해 동적으로 필요한 설정을 추가하거나 변경할 수 있습니다.

js
let secondService = {
    tables: ['second']
};
let threeService = {
    tables: ['three']
};

bm.setService(secondService);
bm.setService(threeService);

// bm.second instanceof MetaTable : true
// bm.three instanceof MetaTable : true

서비스 객체 관리#

서비스 객체를 클래스로 정의하면 재사용성을 높이고, 일관된 구조로 관리할 수 있습니다. 사용 목적에 따라 클래스를 다양한 방식으로 구성할 수 있습니다.

클래스 정의#

서비스 객체는 공통 기능을 포함한 클래스로 정의할 수 있으며, 해당 클래스로부터 객체를 생성한 후 사용자 환경에 맞게 수정하여 재사용할 수 있습니다.

js
// common-service.js
export class CommonService {
    cbFail = function(msg, valid) {
        console.warn ("user failure handling:" + msg);
    };
    cbError = function(msg, status, response) {
        console.error ("User error handling" + msg)
    };
}
js
import { BindModel } from 'logic-bind-model';
import { CommonService } from 'common-service.js';

const svc = new CommonService();
const bm = new BindModel(svc);

상속을 통한 재사용성#

서비스 객체의 공통 부분을 부모 클래스로 정의하면 재사용성을 높일 수 있습니다. 자식 클래스는 부모 클래스의 기능을 확장하거나 재정의할 수 있습니다.

js
// member-service.js
import { CommonService } from 'common-service.js';

export class MemberService extends CommonService {
	constructor(suffix) {
		super();
		
		this.items = {
            idx: 10,
            user_no: { selector: { key: '#user_no' + suffix, type: 'value' } },
            u_name: { selector: { key: '#u_name' + suffix, type: 'value' } },
        };
        this.command = {
            create: {},   // 명시적으로 지정
            read: {
                outputOption: 3,
                cbEnd: (status, cmd, res) => { alert('Normal Processed'); }
            }
        };
        this.mapping = {
            idx: { 
                read: ['valid', 'bind'] 
            },
            u_name: { 
                create: ['valid', 'bind'],
                read: ['output']
            },
            user_no: { 
                create: ['bind'],
                read: ['output'],
            }
        };
	}
	
    preCheck(bindModel) { 
        if (bm.checkSelector().length === 0) return true;
    }
};
  • 객체클래스 정의시 suffix 인자를 지정하여, selector 이름의 중복을 피할 수 있습니다.
  • create: {} 명시적으로 지정한 경우이며, 지정하지 않아도 매핑 시 자동으로 생성됩니다.
js
import { BindModel } from 'logic-bind-model';
import { MemberService } from 'member-service.js';

const svc = new CommonService();
const bm = new BindModel(svc);

bm.url = "/user";
// bm 객체 사용자화
  • 클래스에서 생성한 객체를 모델(BindModel)에 주입하고, 모델객체를 추가 설정하여 사용합니다.

클래스 정의 가이드#

BindModel에서 자주 사용하는 클래스를 정의하고, 이를 상속하여 확장하는 과정을 단계별로 안내합니다.

  • 1단계 : 공통 정의 - 'cbFail', 'cbError' 및 기본 콜백함수를 정의 - 중복 코드 제거를 목표로 공통 기능 구현
  • 2단계 : 독립적인 items 구성 - 공통된 속성을 정의하고, 각 클래스에서 세부적으로 재정의 가능
  • 3단계 : tables, command, mapping의 연계 구성 - tables, command, mapping은 상호 연관성이 높아 계층적으로 함께 설계하는 것이 효율적
  • 4단계 : 전처리 및 초기값 설정 - preCheck와 같은 전처리 과정을 정의하여 폼 유효성 검사 및 초기값 설정에 활용
  • 5단계 : 객체 생성 후 사용자화 - 서버 경로, 환경 설정 등을 객체 생성 후 수정하여 사용자 요구에 맞게 설정

클래스 설계는 사용 목적과요구사항에 맞게 유연하게 변경될 수 있습니다.

검색어를 입력해 보세요.