Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json-server & fake/mock API #13

Open
xyzdata opened this issue Aug 3, 2017 · 23 comments
Open

json-server & fake/mock API #13

xyzdata opened this issue Aug 3, 2017 · 23 comments

Comments

@xyzdata
Copy link
Contributor

xyzdata commented Aug 3, 2017

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
Copy link
Contributor Author

xyzdata commented Aug 3, 2017

port

可选择端口

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

$ json-server --watch db.json --port 7777

@xyzdata
Copy link
Contributor Author

xyzdata commented Aug 3, 2017

image

initialValue="china" ???

initialValue: "china"

@xyzdata
Copy link
Contributor Author

xyzdata commented Aug 3, 2017

@xyz-data xyz-data locked and limited conversation to collaborators Aug 3, 2017
@xgqfrms-GitHub
Copy link
Contributor

xgqfrms-GitHub commented Aug 3, 2017

fetch data

xgqfrms-GitHub/Node-CLI-Tools#15

@xgqfrms-GitHub
Copy link
Contributor

xgqfrms-GitHub commented Aug 3, 2017

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
Copy link
Contributor

xgqfrms-GitHub commented Aug 3, 2017

{
    "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
Copy link
Contributor

xgqfrms-GitHub commented Aug 3, 2017

mlab & free mongodb

free online mongodb

https://mlab.com/

@xgqfrms-GitHub
Copy link
Contributor

xgqfrms-GitHub commented Aug 3, 2017

@xgqfrms-GitHub
Copy link
Contributor

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
Copy link
Contributor

xgqfrms-GitHub commented Aug 3, 2017

API Authentication

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

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

username (not the account name)

@xgqfrms-GitHub
Copy link
Contributor

xgqfrms-GitHub commented Aug 3, 2017

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
Copy link
Contributor

xyz-data/json-server#1

@xgqfrms-GitHub
Copy link
Contributor

xyz-data/json#1

@xgqfrms-GitHub
Copy link
Contributor

xgqfrms-GitHub commented Aug 3, 2017

@xyzdata
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

{
    "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
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

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
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

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
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

@xyzdata
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

get ant form submit values demo

OK

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

@xyzdata
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

解构赋值 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
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

const values = {...};

getUserInfos(values);

// getUserInfos({...values});

@xyzdata
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

@xyzdata
Copy link
Contributor Author

xyzdata commented Aug 4, 2017

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;
        }
    );
};

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants