조건부 미들웨어 처리

omnigi·2022년 3월 12일
0

Api연습

목록 보기
2/8

if로 next를 호출하지 않게 하여 조건부로 원하는 미들웨어까지만 실행 할 수 있습니다.
(로그인 사용자에게만 주는 데이터)

const Koa = require('koa');

const app = new Koa();

app.use((ctx, next) => {
    console.log(ctx.url);
    console.log(1);
    if(ctx.query.authorized !== "1") {
        ctx.status = 401; //Unauthorized
        return;
    }
    next()
});

app.use((ctx, next)=>{
    console.log(2);
    next();
})

app.use(ctx => {
    ctx.body = "hello world";
});

app.listen(4000, () =>{
    console.log("Listening to port 4000");
})

이런식으로 정해둔 인증키를 쿼리에 넣게되면 값을 주는 방식이다.

Koa는 next함수를 호출하면 Promise를 반환합니다.(Koa가 Express와 차별화 되는 부분)

const Koa = require('koa');

const app = new Koa();

app.use((ctx, next) => {
    console.log(ctx.url);
    console.log(1);
    if(ctx.query.authorized !== "1") {
        ctx.status = 401; //Unauthorized
        return;
    }
    next().then(()=>{
        console.log("END")
    });
    //추가된 부분
});

app.use((ctx, next)=>{
    console.log(2);
    next();
})

app.use(ctx => {
    ctx.body = "hello world";
});

app.listen(4000, () =>{
    console.log("Listening to port 4000");
})

/// 결과
?authorized=1
1
2
END
/favicon.ico
1

async/await 사용하기

Koa는 async/await를 정식으로 지원합니다 !

const Koa = require('koa');

const app = new Koa();

app.use(async (ctx, next) => {
    console.log(ctx.url);
    console.log(1);
    if(ctx.query.authorized !== "1") {
        ctx.status = 401; //Unauthorized next().then(()=>{console.log("END")});
        return;
    }
    await next();
    console.log("END")
});

app.use((ctx, next)=>{
    console.log(2);
    next();
})

app.use(ctx => {
    ctx.body = "hello world";
});

app.listen(4000, () =>{
    console.log("Listening to port 4000");
})

0개의 댓글