xyz-data / redux-seeds

Redux Seeds : React family's all in one!
MIT License
0 stars 0 forks source link

json-server & fake/mock API #13

Open xyzdata opened 6 years ago

xyzdata commented 6 years ago

json-server & fake/mock API


$ npm i -g json-server

$ npm i -D json-server

https://github.com/typicode/json-server

new


{
    "name": "test-db",
    "version": "1.0.0",
    "description": "json-server & fake/mock api",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "echo \"JSON-server ready running...\n\" && json-server --watch db.json",
        "infos": "echo JSON-server ready running...\n",
        "jsondb": "json-server --watch db.json --port 7777",
        "open": "start  http://localhost:7777/posts/1",
        "db": "npm run infos && npm run open && npm run jsondb"
    },
    "author": "xgqfrms",
    "license": "MIT",
    "devDependencies": {
        "json-server": "^0.12.0"
    }
}

old

{
    "name": "test-db",
    "version": "1.0.0",
    "description": "json-server & fake/mock api",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "echo \"JSON-server ready running...\n\" && json-server --watch db.json",
        "infos": "echo JSON-server ready running...\n",
        "db": "npm run infos && npm run open && npm run jsondb",
        "jsondb": "json-server --watch db.json",
        "open": "start  http://localhost:3000/posts/1"
    },
    "author": "xgqfrms",
    "license": "MIT",
    "devDependencies": {
        "json-server": "^0.12.0"
    }
}

db


{
    "posts": [
        {
        "id": 1,
        "title": "json-server",
        "author": "typicode"
        }
    ],
    "comments": [
        {
            "id": 1,
            "body": "some comment",
            "postId": 1
        }
    ],
    "profile": {
        "name": "typicode"
    }
}
xyzdata commented 6 years ago

port

可选择端口

https://github.com/xgqfrms-GitHub/json-server#可选择端口


$ json-server --watch db.json --port 7777
xyzdata commented 6 years ago

image

initialValue="china" ???

initialValue: "china"

xyzdata commented 6 years ago

https://codepen.io/xyz-data/pen/breOBz?editors=0011

xgqfrms-GitHub commented 6 years ago

fetch data

https://github.com/xgqfrms-GitHub/Node-CLI-Tools/issues/15

xgqfrms-GitHub commented 6 years ago

Error

new Error([message[, fileName[, lineNumber]]])


try {
    throw new Error("Whoops!");
} catch (e) {
    alert(e.name + ": " + e.message);
}

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Error

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/throw

xgqfrms-GitHub commented 6 years ago

{
    "posts": [
        {
            "id": 1,
            "title": "json-server",
            "author": "typi-code"
        },
        {
            "id": 2,
            "title": "json server",
            "author": "typi code"
        }
    ],
    "datas": [
        {
            "id": 1,
            "name": "typicode",
            "password": "abc123"
        },
        {
            "id": 2,
            "name": "xgqfrms",
            "password": "xyz123"
        },
        {
            "id": 3,
            "name": "xyzdata",
            "password": "ufo123"
        }
    ]
}
xgqfrms-GitHub commented 6 years ago

mlab & free mongodb

free online mongodb

https://mlab.com/

xgqfrms-GitHub commented 6 years ago

MongoDB CURD

???

https://github.com/xyzdata/json-server/tree/master/prod-app

xgqfrms-GitHub commented 6 years ago

image

API

http://docs.mlab.com/data-api/


"q" example - return all documents with "active" field of true:
https://api.mlab.com/api/1/databases/my-db/collections/my-coll?q={"active": true}&apiKey=myAPIKey

"c" example - return the count of documents with "active" of true:
https://api.mlab.com/api/1/databases/my-db/collections/my-coll?q={"active": true}&c=true&apiKey=myAPIKey

"f" example (include) - return all documents but include only the "firstName" and "lastName" fields:
https://api.mlab.com/api/1/databases/my-db/collections/my-coll?f={"firstName": 1, "lastName": 1}&apiKey=myAPIKey

"f" example (exclude) - return all documents but exclude the "notes" field:
https://api.mlab.com/api/1/databases/my-db/collections/my-coll?f={"notes": 0}&apiKey=myAPIKey

"fo" example - return a single document matching "active" field of true:
https://api.mlab.com/api/1/databases/my-db/collections/my-coll?q={"active": true}&fo=true&apiKey=myAPIKey

"s" example - return all documents sorted by "priority" ascending and "difficulty" descending:
 https://api.mlab.com/api/1/databases/my-db/collections/my-coll?s={"priority": 1, "difficulty": -1}&apiKey=myAPIKey

"sk" and "l" example - sort by "name" ascending and return 10 documents after skipping 20
 https://api.mlab.com/api/1/databases/my-db/collections/my-coll?s={"name":1}&sk=20&l=10&apiKey=myAPIKey

Your API key, including any clients from which your API key can be recovered, should not be distributed to non-administrators.

xgqfrms-GitHub commented 6 years ago

API Authentication

http://docs.mlab.com/data-api/#authentication

https://mlab.com/user?username=xyzdata

username (not the account name)

xgqfrms-GitHub commented 6 years ago

OK


const myAPIKey = `YpeswCDPr9CvDfmeIuawnh-iD5-oH0_G`;
const url = `https://api.mlab.com/api/1/databases/xyzdata_crm/collections/test?q={}&apiKey=${myAPIKey}`;
// collection === test
// q={} === all

const getdata = () => {
    fetch(url, {
        method: 'GET',
        mode: 'no-cors'
    }).then(
        (response) => {
            console.log(`fetch response`, response);
            return response.json();
        }
    ).then(
        (json) => {
            console.log(`fetch json`, json);
            let data = JSON.stringify(json);
            return data;
        }
    ).catch(
        (err) => {
            const color = `
                color: red;
                background: rgba(125, 125, 125, 0.7);
                font-size: 23px;
            `;
            console.log(`%c Whoops, An Error occurred!`, color, err);
            throw new Error("Whoops, An Error occurred!", err);
        }
    );
};

image

xgqfrms-GitHub commented 6 years ago

https://github.com/gildata/json-server/issues/1

xgqfrms-GitHub commented 6 years ago

https://github.com/gildata/json/issues/1

xgqfrms-GitHub commented 6 years ago

https://github.com/xyzdata/json/blob/master/index.js

xyzdata commented 6 years ago

{
    "datas": [
        {
            "key": "1",
            "uname": "xray",
            "utype": "内部用户",
            "uid": 17,
            "lname": "西湖区",
            "pnum": "18123456789",
            "email": "clarence.gray@example.com",
            "vdate": "2017-01-01~2017-12-31",
            "activation": "是"
        },
        {
            "key": "2",
            "uname": "Sidney",
            "utype": "外部用户",
            "uid": 23,
            "lname": "湖底公园",
            "pnum": "18123456789",
            "email": "clarence.gray@example.com",
            "vdate": "2017-01-01~2017-12-31",
            "activation": "否"
        },
        {
            "key": "3",
            "uname": "Joe Black",
            "utype": "内部用户",
            "uid": 32,
            "lname": "Sidney No. 1 Lake Park",
            "pnum": "18123456789",
            "email": "clarence.gray@example.com",
            "vdate": "2017-01-01~2017-12-31",
            "activation": "是"
        },
        {
            "key": "4",
            "uname": "xray",
            "utype": "外部用户",
            "uid": 23,
            "lname": "西湖公园1号",
            "pnum": "18123456789",
            "email": "clarence.gray@example.com",
            "vdate": "2017-01-01~2017-12-31",
            "activation": "是"
        },
        {
            "key": "5",
            "uname": "Sidney",
            "utype": "内部用户",
            "uid": 66,
            "lname": "西湖湖底",
            "pnum": "18123456789",
            "email": "clarence.gray@example.com",
            "vdate": "2017-01-01~2017-12-31",
            "activation": "否"
        },
        {
            "key": "6",
            "uname": "Joe Black",
            "utype": "外部用户",
            "uid": 18,
            "lname": "Sidney No. 1 Lake Park",
            "pnum": "18123456789",
            "email": "clarence.gray@example.com",
            "vdate": "2017-01-01~2017-12-31",
            "activation": "是"
        }
    ]
}
xyzdata commented 6 years ago

const url = `http://localhost:7777/datas/`;
const getUserId = (uid) => {
    let new_url = `${url}?id=${uid}`;
    return fetch(new_url, {
        method: 'GET'
    }).then(
        (response) => response.json()
    ).then(
        (json) => {
            console.log(`get id data`, json);
            console.log(`get id data json[0]`, json[0]);
            // maps array data
            console.log(`get id data, json.length`, json.length);
            return json;
        }
    );
};

const xfetchSearch = {
    getUserId
};

let data = xfetchSearch.getUserId(17);

// ??? how to the returned objects array data ???

/* 

{
    "key": "1",
    "uname": "xray",
    "utype": "内部用户",
    "uid": 17,
    "lname": "西湖区",
    "pnum": "18123456789",
    "email": "clarence.gray@example.com",
    "vdate": "2017-01-01~2017-12-31",
    "activation": "是"
},

*/

image

PromiseValue ???

xyzdata commented 6 years ago

PromiseValue

Test OK

https://stackoverflow.com/questions/28916710/what-does-promisevalue-mean-in-javascript-console-and-how-to-do-i-get-it

https://stackoverflow.com/a/28917161/8202629


// let data = fetchSearch.getUserId(17).PromiseValue;

let data = fetchSearch.getAll();

let data = [];
fetchSearch
.getAll()
.then((json) => (data = json));

fetchSearch.getAll().then(
    (json) => {
        data = json;
        return data;
    }
);
xyzdata commented 6 years ago

https://stackoverflow.com/a/45499066/8202629

xyzdata commented 6 years ago

get ant form submit values demo

OK

https://codepen.io/xyzdata/pen/breOBz?editors=0011

xyzdata commented 6 years ago

解构赋值 in deepth

从作为函数实参的对象中提取数据

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

// 解构赋值 ({a, b, ...rest} = {a:1, b:2, c:3, d:4});

let values = {
    loginName: "undefined",
    userId: "undefined",
    userName: "undefined",
    phoneNumber: "undefined",
    email: "undefined",
    validDate: "undefined"
};

const search_obj = {
    loginName,
    userId,
    userName,
    phoneNumber,
    email,
    validDate
};

const search_obj = values;

const test = (...search_obj) => {
    console.log(`userId`, userId);
    console.log(`userName`, userName);
    console.log(`email`, email);
};

// 从作为函数实参的对象中提取数据

const user = { 
    id: 42, 
    displayName: "jdoe",
    fullName: { 
        firstName: "John",
        lastName: "Doe"
    }
};

// Object same key name, auto match value
const userId(
    {
        id
    }
) => id;

console.log("userId: " + userId(user));
// "userId: 42"

// customized Object keys names
const whois = (
    {
        displayName: dName, 
        fullName: {
            firstName: fName
        }
    }
) => {
    // console.log(displayName + " is " + firstName);
    // Uncaught ReferenceError: displayName is not defined
    console.log(dName + " is " + fName);
};

whois(user); 
// "jdoe is John"

let values = {
    loginName: "undefined",
    userId: "undefined",
    userName: "undefined",
    phoneNumber: "undefined",
    email: "undefined",
    validDate: "undefined"
};

const search_obj = Object.assign({}, values);

const test = (...search_obj) => {
    console.log(`userId`, userId);
    console.log(`userName`, userName);
    console.log(`email`, email);
};

/*

Object {
    loginName: undefined,
    userId: undefined,
    userName: undefined,
    phoneNumber: undefined,
    email: undefined,
    validDate: undefined
}

*/
export const getUserInfos = (uid, uname, email, phone) => {
    let new_url = `${url}?uid=${uid}&uname=${uname}&$email=${email}&phone=${phone}`;
    return fetch(new_url, {
        method: 'GET'
    }).then(
        (response) => response.json()
    ).then(
        (json) => {
            console.log(`get id data`, json);
            console.log(`get id data json[0]`, json[0]);
            // maps array data
            console.log(`get id data, json.length`, json.length);
            return json;
        }
    );
};
xyzdata commented 6 years ago
const values = {...};

getUserInfos(values);

// getUserInfos({...values});
xyzdata commented 6 years ago

https://github.com/pmg1989/dva-admin/blob/master/src/components/Search/Search.js

https://github.com/pmg1989/dva-admin/issues/18

xyzdata commented 6 years ago

export const getUserInfos = (uid, uname, lname, utype, email, pnum, vdate, activation) => {
/*     let new_url = `
        ${url}
        ?uid=${uid}&uname=${uname}&lname=${lname}&utype=${utype}
        &email=${email}&pnum=${pnum}&vdate=${vdate}&activation=${activation}
    `; */
    let new_url = url;
    // all
    if(uid){
        new_url = `${url}?uid=${uid}`;
    }else if(uname){
        new_url = `${url}?uname=${uname}`;
    }else if(lname){
        new_url = `${url}?lname=${lname}`;
    }else if(utype){
        let new_utype = "";
        (utype === "innerUser") ? (new_utype="内部用户") : (new_utype="外部用户");
        new_url = `${url}?utype=${new_utype}`;
    }else if(lname){
        new_url = `${url}?lname=${lname}`;
    }else if(email){
        new_url = `${url}?email=${email}`;
    }else if(pnum){
        new_url = `${url}?pnum=${pnum}`;
    }else if(vdate){
        new_url = `${url}?vdate=${vdate}`;
    }
    // 如果用户什么都不输入, 传递后端一个空对象 {};
    // 如果某个字段有值,才把该字段封装到对象中,{key1: "value1", key2: "value2"}
    return fetch(new_url, {
        method: 'GET'
    }).then(
        (response) => response.json()
    ).then(
        (json) => {
            console.log(`%c get getUserInfos data`, color_css, json);
            console.log(`get getUserInfos data json[0]`, json[0]);
            // maps array data
            console.log(`get getUserInfos data, json.length`, json.length);
            return json;
        }
    );
};