대부분 언어에서는 순환 참조를 금지하고 있다.

당연히 무한 루프를 돌아서 그렇겠지만

nodeJs는 허용하고 있다.

DB모델들 같은 경우는 서로 참조하고 있는 경우가 많기 때문이다.

하지만 일반적으로는 순환 참조가 발생하지 않게 하고 클래스를 잘 나눠야 겠지만

그렇게 하고 싶지 않을 때가 있다.

lazy export로 해결하는 방법이 있다. 정말 특수한 경우에만 쓰자

https://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js

 

How to deal with cyclic dependencies in Node.js

I've been working with nodejs lately and still getting to grips with the module system so apologies if this is an obvious question. I want code roughly like the following below: a.js (the main fil...

stackoverflow.com

https://blog.outsider.ne.kr/1283

 

Node.js의 순환 의존성 :: Outsider's Dev Story

코드를 모듈화해서 작성하다 보면 서로 간에 의존성을 갖게 되는데 이러다 보면 순환 의존성을 가질 수 있다. A 파일이 B를 참조하는데 B 파일이 다시 A 파일을 참조할 수 있고 좀 더 복잡하게는 의도치 않게 A가...

blog.outsider.ne.kr

 

'nodeJS' 카테고리의 다른 글

axios vs fetch #1  (0) 2019.11.17
npm 설치 가능한 버전 보기  (0) 2019.08.16
Conflicts in NextJs and Routing-Controllers  (0) 2019.07.30
nodeJs 구조  (0) 2018.04.18
npm --save --save-dev  (0) 2018.04.14

OOP의 중요한 원칙 중하나가 인터페이스를 잘 만드는 것이다.

아무리 고민을 해봐도 정답이 없고 계속 이리 저리 바꾸며 시간을 보낸적이 많다.

아래는 http://www.nextree.co.kr/p6960/ 에서 Open Close Principle 부분을 인용해 온 글이다.

```

 

  1. 확장되는 것과 변경되지 않는 모듈을 분리하는 과정에서 크기 조절에 실패하면 오히려 관계가 더 복잡해 질 수 있습니다. 설계자의 좋은 자질 중 하나는 이런 크기 조절과 같은 갈등 상황을 잘 포착하여 (아깝지만) 비장한 결단을 내릴 줄 아는 능력에 있습니다.

  2. 인터페이스는 가능하면 변경되어서는 안 됩니다. 따라서 인터페이스를 정의할 때 여러 경우의 수에 대한 고려와 예측이 필요합니다. 물론 과도한 예측은 불필요한 작업을 만들고, 보통 이 불필요한 작업의 양은 상당히 크기 마련입니다. 따라서 설계자는 적절한 수준의 예측 능력이 필요한데, 설계자에게 필요한 또 하나의 자질은 예지력입니다.

  3. 인터페이스 설계에서 적당한 추상화 레벨을 선택해야 합니다. 우리는 추상화라는 개념에 '구체적이지 않은' 정도의 의미로 약간 느슨한 개념을 갖고 있습니다. 그래디 부치(Grady Booch)에 의하면 ‘추상화란 다른 모든 종류의 객체로부터 식별될 수 있는 객체의 본질적인 특징’이라고 정의하고 있습니다. 즉, 이 '행위'에 대한 본질적인 정의를 통해 인터페이스를 식별해야 합니다.

```

 

1메서드 1인터페이스로 한다면 인터페이스 관련 OOP원칙에 잘 맞을 것이다.

하지만 뭐하나 만들 때마다 그 많은 인터페이스를 다 적어주는 것도 코딩을 피곤하게 만든다.

모든 상황에서 사용하기 편한 인터페이스는 존재하지 않을 수 있다.

수 많은 상황속에서 가장 자주 쓰고 특수한 상황을 잘 대처해 나갈 수 있는 인터페이스를 만드려면

도메인에 대한 이해가 중요하다.

하지만 도메인에 대한 완전한 이해는 많은 시간이 걸리는 일이다.

FP라면 이러한 상황을 좀 더 유연하게 대처할 수 있을 것이다.

견고함과 목적성의 불확실성은 다소 가질 수 있겠지만 FP를 통해 OOP를 구현하는 것이 쉬워 보인다는 생각이든다.

 

 

'개발 방법론' 카테고리의 다른 글

기능 설명서와 우선 순위  (0) 2017.12.19
javascript package  (0) 2017.12.10

sequelize로 findAll 해서 얻은 객체는 순수한 DB 자료구조가 아니다

여러 함수화 여러 상태가 복합적으로 얽혀있다.

이걸 다 쓰냐고 말한다면 거의 그렇지 않다

1. sequelize 객체 - 옵션 없이 그냥 find로 나온 객체

2. find option에서  raw: true를 주었을 경우

3. get() 메서드로 얻는 방법

4. toJSON()으로 얻는 법

5. dataValues로 얻는 법

 

뭔가 통일을 해야 할 것 같은데 가장 범용적인 방법이 뭔지 혼란 스럽다.

 

// App version 1 (current version)

var onError = function (error) {
    console.log("An error occurred. " + error);
};

var onInstallSuccess = function () {
    console.log("Installation succeeded.");
};

var onPackageDownloaded = function (localPackage) {
    // Install regular updates after someone navigates away from the app for more than 2 minutes
    // Install mandatory updates after someone restarts the app
    localPackage.install(onInstallSuccess, onError, { installMode: InstallMode.ON_NEXT_RESUME, minimumBackgroundDuration: 120, mandatoryInstallMode: InstallMode.ON_NEXT_RESTART });
};

var onUpdateCheck = function (remotePackage) {
    if (!remotePackage) {
        console.log("The application is up to date.");
    } else {
        // The hash of each previously reverted package is stored for later use. 
        // This way, we avoid going into an infinite bad update/revert loop.
        if (!remotePackage.failedInstall) {
            console.log("A CodePush update is available. Package hash: " + remotePackage.packageHash);
            remotePackage.download(onPackageDownloaded, onError);
        } else {
            console.log("The available update was attempted before and failed.");
        }
    }
};

window.codePush.checkForUpdate(onUpdateCheck, onError);

//------------------------------------------------

// App version 2 (updated version)

var app = {
    onDeviceReady: function () {
        // Calling this function is required during the first application run after an update.
        // If not called, the application will be reverted to the previous version.
        window.codePush.notifyApplicationReady();
        // ...
    }
}



'FrontEnd' 카테고리의 다른 글

We can’t directly animate gradients using the CSS transition property  (0) 2019.05.23
react-vis 에러 모음  (0) 2019.03.30
초간단 그림으로 보는 flux architecture  (0) 2018.07.25
lodash  (0) 2018.06.05
html unselectable  (0) 2018.05.13

시퀄라이즈에서는 outer join 한 테이블 컬럼을 join된 결과에서 where 구문으로 불러오려고 할 때

그냥 join한 테이블 이름 또는 alias로 찾을 수가 없다.

이 경우 '$nested.column$' 문법으로 볼러 올 수 있다.


eg.) where: { $UserDetail.address$: { [Op.like]: '%영등포%' } }


어쩌다가 이렇게 불편하게 됐는지 언제한번 들여다 보아야 겠다.




const TRANSACTION_NAMESPACE = "sequelize-transaction";

const cls = require("continuation-local-storage"),
    namespace = cls.createNamespace(TRANSACTION_NAMESPACE);

SequelizeOrigin.useCLS(namespace);

export const ns = namespace;

export const sequelize = new Sequelize({
    host,
    database,
    dialect: "mysql",
    username,
    password,
    modelPaths: [
        path.resolve(__dirname, "..", "model/**/*.repository{.ts,.js}"),
    ],
    logging: !profile.isProduction && false,
    modelMatch: (filename: string, member: string) => {
        if (filename === member) {
            return true;
        }

        const removeRepository = filename.split(".")[0];
        return removeRepository === member;
    },
});

export const transactionManager: TransactionManager = {
    transaction<T>(fn, options = {propagation: "REQUIRED"}) {
        if (options.propagation !== "REQUIRED") {
            return sequelize.transaction(() => fn());
        }

        const tx = cls.getNamespace(TRANSACTION_NAMESPACE).get("transaction");
        return tx ? fn() : sequelize.transaction(() => fn());
    },
};


const foo = <T extends {}>(x: T): T => x


<>가 HTML태그가 아니라 제네릭이라는 힌트를 extends로 주면 된다.

type Foo = {
    isSubscribed: boolean
    [field: string]: string
}


이렇게 쓰면 isSubscribed 가 index signaure 형식에 맞지 않아서 적용할 수가 없다.


type Foo = {
    isSubscribed: boolean
} & {
    [field: string]: string
}


intersection으로는 선언이 가능하다. 


const bar: Foo = {
    isSubscribed: true,
    name: "wook"
}


하지만 이런식으로 변수 설정을 할 수 없다.


const bar: Foo = Object.assign(
    {
        isSubscribed: true,
    },
    {
        name: "wook"
    }
);


이런식으로 할당하던지


declare const bar: Foo;

bar.isSubscribed = true;
bar.name = "wook";


이런식으로 선언해야 한다.

git config credential.helper store

https://help.github.com/articles/caching-your-github-password-in-git/#platform-linux


+ Recent posts