· 6 years ago · Sep 03, 2019, 03:34 AM
1import AsyncStorage from '@react-native-community/async-storage';
2import SQLite from 'react-native-sqlite-storage';
3import ApiService from '../../service/ApiService';
4
5SQLite.DEBUG(true);
6SQLite.enablePromise(true);
7
8let districts;
9
10// district 테이블을 제거한다.
11_dropTable = (tx) => {
12 tx.executeSql(`DROP TABLE district`)
13 .then(() => {
14 console.log('sqlite DROP TABLE done');
15 })
16 .catch((error) => {
17 console.log('sqlite DROP TABLE error: ', error);
18 });
19}
20
21// district 테이블을 새로 생성한다.
22_createTable = (tx) => {
23 tx.executeSql(`CREATE TABLE IF NOT EXISTS district (
24 "address" TEXT NOT NULL UNIQUE,
25 PRIMARY KEY("address")
26 )`)
27 .then(() => {
28 console.log('sqlite CREATE TABLE done');
29 })
30 .catch((error) => {
31 console.log('sqlite CREATE TABLE error: ', error);
32 });
33}
34
35// 동읍면 데이터 전체를 테이블에 입력한다.
36_insertAddress = (tx) => {
37 districts.forEach((item, index, array) => {
38 tx.executeSql(`INSERT OR REPLACE INTO district (address) VALUES ("${item}")`)
39 .catch((error) => {
40 console.log('sqlite INSERT INTO error: ', error);
41 });
42 });
43}
44
45exports.updateAddressList = async (newAddressApiUrl) => {
46 console.log(`update address list. addressApiUrl=${newAddressApiUrl}`);
47
48 // json으로 된 동읍면 데이터를 불러온다.
49 districts = await ApiService.getJsonDataByUrl(newAddressApiUrl);
50
51 // SQLite db를 연다.
52 await SQLite.openDatabase(
53 {
54 name: 'fineDustLocalDB.db',
55 createFromLocation: 1,
56 },
57 (DB) => {
58 console.log('success opening fineDustLocalDB')
59
60 // 우선 기존에 존재하던 district 테이블 제거
61 DB.transaction(this._dropTable)
62 .then(() => {
63 console.log('drop table transaction done');
64 })
65 .catch((error) => {
66 console.log('drop table transaction fail: ', error);
67 });
68
69 // 새로운 district 테이블 생성
70 DB.transaction(this._createTable)
71 .then(() => {
72 console.log('create table transaction done');
73 })
74 .catch((error) => {
75 console.log('create table transaction fail: ', error);
76 });
77
78 // 새로 들어온 동읍면 데이터 입력
79 DB.transaction(this._insertAddress)
80 .then(() => {
81 console.log('insert row transaction done');
82 })
83 .catch((error) => {
84 console.log('insert row transaction fail: ', error);
85 });
86 },
87 error => {
88 console.error(error);
89 }
90 );
91
92 // 로컬 스토리지에 새로운 주소 리스트 파일 정보
93 await AsyncStorage.setItem('@address_api_url', newAddressApiUrl);
94}