본문 바로가기
Project/홈페이지

[TODO] google sheet API 연동

by 햄과함께 2019. 3. 17.
320x100

API 연동(Axios)


npm install --save axios
cs

위 명령어로 axios 설치

// src/api/apiConfig.ts
export const config = {
    baseUrl: 'https://sheets.googleapis.com/v4/spreadsheets/',
    sheetId: '{sheetId}',
    sheetName: '{sheetName}',
    apiKey: '{apiKey}'
cs
API에 사용할 정보를 따로 파일로 만들었다. {} 안에 적은 정보는 mock 데이터이다. 

// src/api/googleSheetApi.ts
 
import axios, { AxiosPromise } from 'axios'
import { TodoResponse } from '../store/modules/todo';
import { config } from './apiConfig';
 
const googleSheetApi = axios.create({
    baseURL: config.baseUrl
})
 
export function fetchTodos(): AxiosPromise<TodoResponse> {
    const params = { key: config.apiKey }
    return googleSheetApi.get(`${config.sheetId}/values/${config.sheetName}`, { params });
cs
axios로 통신하는 코드를 위와 같이 만들었다.
baseUrl을 이용해 googleSheetApi를 만들고
spread sheet의 정보를 가져오는 googleAPi를 호출하는 fetchTodos라는 함수를 만들었다.

//src/api/index.ts
import * as googleSpreadSheetApi from './googleSheetApi'
 
export {
    googleSpreadSheetApi
}
cs
다른 API도 만들것을 생각해서 API를 export하는 파일을 모아놨다.

// tsconfig.json
{
    "compilerOptions": {
         // ...
        "baseUrl""src",
        "paths": {
            "@api/*": [ // @api path 
                "api/*"
            ]
        },
    },
    // ...
}
cs
tsconfig에는 api를 호출시 @api로 접근할 수 있게 path alias를 추가했다.
paths를 추가할 시 baseUrl을 지정하지 않으면 에러가 떠서 src를 baseUrl로 지정해뒀다.



Vuex(State, Mutate, Action)


// src/store/modules/todo.ts
 
import { ActionTree, Dispatch, Commit } from 'vuex';
import { googleSpreadSheetApi } from '../../api';
 
export const namespaced = true;
 
export class TodoItem {
    name: string = '';
    todo: string = '';
 
    constructor(name: string, todo: string) {
        this.name = name;
        this.todo = todo;
    }
}
 
export interface TodoResponse {
    values: string[]
}
 
interface State {
    todos: TodoItem[]
}
 
export const state: State = {
    todos: []
}
 
export const getters = {};
 
export const mutations = {
    SET_TODO(state: State, todos: string[]) {
        todos.forEach((todo, index) => {
            if (index == 0return;
            state.todos.push(new TodoItem(todo[0], todo[1]));
        });
    }
};
 
export const actions: ActionTree<State, any> = {
    getTodos({ commit }): void {
        googleSpreadSheetApi.fetchTodos()
            .then(response => {
                commit('SET_TODO', response.data.values)
            })
    }
cs
APi를 호출하는 방식은 Action에서 api를 호출하고 그 결과로 mutation을 이용해 state 값을 변경시킨다.
SET_TODO mutation에는 가져온 정보에서 0번째 배열을 제외한 정보들로 TodoItem 객체를 만들어서 todos state에 넣어줬다.

// src/store/index.ts
 
import * as todo from './modules/todo';
 
Vue.use(Vuex);
 
export const store = new Vuex.Store({
    //...
    modules: {
        // ...
        todo // add
    }
}
cs
todo vuex모듈을 등록하면 끝.


Component 수정

// src/components/Todo/index.ts
 
import { Vue, Component, Prop } from "vue-property-decorator";
import { mapState, mapActions } from "../../../node_modules/vuex";
 
@Component({
    template: require('./Todo.html'),
    computed: {
        ...mapState('todo', ['todos']) // state 추가
    },
})
export default class Todo extends Vue {
    created() {
        this.$store.dispatch('todo/getTodos'); // todo 모듈의 getTodos 액션 
    }
 
}
cs

기존에 작성한 Todo 컴포넌트를 위와 같이 수정했다.
mock 데이터를 삭제하고 created() 때, vuex의 getTodos Action을 호출해서 todos state를 세팅한다.
state 세팅이 끝나면 화면에 보여지게 될 것이다.

google sheet 정보

화면 출력.

값이 잘 세팅되서 하면에 보이는 것을 확인할 수 있다.




참고 깃허브 : add axios use google sheet API


위 깃허브에 올린 프로젝트를 그대로 실행시키면 API를 제대로 불러오지 못합니다.

왜냐하면 src/api/apiConfig.ts에 실제 사용하는 값을 세팅하지 않았기 때문입니다.

보안을 위해 config의 baseUrl을 제외한 sheetId, sheetName, apiKey는 mock데이터를 넣어두었습니다.

실제로 돌려보고 싶다면 이전 포스팅을 보고 실제 key를 발급받아서 해보시길 바랍니다.




git update-index --assume-unchanged {파일이름}
git update-index --assume-unchanged src/api/apiConfig.ts
cs

참고로 특정 파일의 추적을 끊고 싶을 때는 위와 같은 명령어를 사용한다.

.gitignore 파일에 파일을 등록하면 될 줄 알았는데 원격 저장소에서도 삭제가 되서 원격 브랜치의 파일은 그대로 두고 로컬에서 해당 파일이 변경되는 것을 무시하기 위해서 사용했다.

320x100

댓글