1.1.0 • Published 1 year ago

fdtigermaster-shop-admin-sdk v1.1.0

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

FDTigerMasger - Admin SDK package

pipeline status coverage report

API Document

API Document

get start

  • install

    npm install --save fdtigermaster-admin-sdk --registry http://104.154.20.200:4873
  • update

    npm update --save fdtigermaster-admin-sdk --registry http://104.154.20.200:4873
  • import

    import tigermaster from 'fdtigermaster-admin-sdk'

App

  • Initialize application

    app must been initialize before use, you can initialize by call

    //use then
    tigermaster.initializeApp({
        stage: "local"
    }).then(() => {
        ...other work
    })
    
    //or async await
    await tigermaster.initializeApp({
        stage: "local"
    })

Auth

You can use Auth component to manage your user instance, it provide basic login/logout, create, token resolve and token cookie management functionallity. You can get Auth global instance by

import tigermaster from 'fdtigermaster-admin-sdk';
const auth = tigermaster.auth;
//...doing work with auth component

Auth component will start initializing asynchronously when you initialize the app, and you can use onReady hook to have callback when ready, during initialize, Auth will try to recover last logined user token and data from the cookie if possable, thus, it is recommanded to check current user status after auth ready.

const auth = tigermaster.auth;
auth.onReady(() => {
    if(auth.currentUser !== undefined){
        // user recovered
    }else{
        // user recover fail
    }
})
  • Create user and get user

    import tigermaster from 'fdtigermaster-admin-sdk';
    const userId = await tigermaster.auth.createUser('phone', {
        email: 'mail',
        name: 'name',
        roleId: 1
    });
    const user = await tigermaster.auth.getUserById(userId);
  • Current user

    Current user represent the global login user that currently using this system. Every call on protected API is auth by this user so make sure you have a valid user before invoke any protect call. You can get current user by

    const user = auth.currentUser;
    
    user.id; //user unique id
    user.token; //authorized token
    user.data; //other data

    It is possable that current user been revoked by backend after update, deactived or other operation. You can use onUserAuthLost to subscribe auth lost event and handle this error.

    const unsubscribe = auth.onUserAuthLost(()=>{
        //handle lost event.
    });
    unsubscribe(); //unsubscribe the event
  • Login and logout

    you can login user by calling loginWithPhoneAndPassword, it will return global login user if success and throw error if fail.

    try{
        const user = await auth.loginWithPhoneAndPassword(phone, password);
    }catch(err){
        console.log(err);
    }

    To logout a user call

    auth.logout();

User

When you use getUserById in the auth component, it will return a User object that can be use to update or delete user related data.

  • Upload and delete user image

    You can upload or delete user image like following example.

    import tigermaster from 'fdtigermaster-admin-sdk';
    const user = await tigermaster.auth.getUserById('userId');
    const file = input.file[0];
    const imageId = await user.licenseUpload('userId', file, 'pictureDesc');
    await user.licenseDelete(imageId);

Database

Database component allow you to query data in database by chaining different query condiction, the following is the example to get database instance and query top 100 user that using android and sex is not set, result order by userId descending, notice that all field here use database format(snake case).

import tigermaster from 'fdtigermaster-admin-sdk';
const database = tigermaster.database;
const result = await database
    .query("user")
    .with("user_device")
    .link("user.id", "user_device.uid")
    .where("user_device.device", "=", 0)
    .where("user.sex", "IS NULL")
    .orderBy("user.id", "desc")
    .limit(0, 100)
    .get();

The return of Database query is a QueryResult object, it has three field.

//contain array of query result
QueryResult.data;
//number of result, equal to QueryResult.data.length
QueryResult.queryRows;
//total number of record in the database by this query condiction
QueryResult.totalCount;
  • query

    query declare the entity we want in the QueryResult and each query can only have one query entity. The simplest query can be preformed like the following, return all record in target table.

    database.query("user").get();
  • with and link

    with is use for declaring other related table that use in this query, and link declare the relation between query and with, each table referencing in link, where and orderBy will be check whether been declared in query or with then reject if missing declaration. The following example is query with relation and it's equlevent SQL string

    //query
    database
        .query("user")
        .with("user_device")
        .link("user.id", "user_device.uid")
        .where("user_device.device", "=", 0);
    //SQL
    SELECT `user`.*
    FROM `user`, `user_device`
    WHERE `user`.`id` = `user_device`.`uid`
    AND `user_device`.`device` = 0;
    //error example
    database
        .query("user")
        .link("user.id", "user_device.uid")// error, user_device not defined in query or with
        .where("user_note.id", "=", 0)// error, user_note not defined in query or with
  • where

    where add condiction to this query and it support following operator, and preform query with where condiction like the example.

    // support operator: =, !=, <, <=, >, >=, LIKE, IS NULL, IS NOT NULL
    //query with where condiction
    const result = await database
        .query("user")
        .with("user_device")//don't forget declare referanced table here
        .link("user.id", "user_device.uid")
        .where("user_device.device", "=", 0)
        .where("user.addressCity", "IN", ["台北市", "新北市"])
        .where("user.sex", "IS NULL");// IS NULL and IS NOT NULL doesn't need third augument
  • orderBy

    orderBy sort the result according to your setting and it support both asc and desc direction. The following example show how to preform a query with roleId in ascending order.

    const result = await database
        .query("user")
        .orderBy("user.role_id", "asc");
  • limit

    limit control number of result in a signal query, The following example show how to preform a query start form 50th and return 100 record.

    //suppose there are 1000 record in database
    const result = await database
        .query("user")
        .limit(50, 100);
    console.log(result.queryRows);// 50
    console.log(result.totalCount);// 1000
  • rawQuery

    Preform no warp native sql query.

    //suppose there are 1000 record in database
    const result = await database
        .rawQuery("select user.* from user")
        .get()
    console.log(result.data);
    console.log(result.totalCount);// 1000

Services

Services component contain basic operation of Skill and WorkingCategory, the following is the example to get Services instance.

import tigermaster from 'fdtigermaster-admin-sdk';
const services = tigermaster.services;
  • Skill

    You can use Skill component to creat, update and get signal SkillItem.

    import tigermaster from 'fdtigermaster-admin-sdk';
    const skill = tigermaster.services.Skill;
    //create skill
    await skill.create({
        id: "TM-X01010",
        description: "通水管馬桶等等"
    });
    //create skill
    await skill.update({
        id: "TM-X01010",
        active: 0
    });
    //get skill item by it
    conse skillItem = await skill.get("TM-X01010");
  • Skill batch upload and download

    In skill componemt, you can also upload or download csv formatted skill file, the following is example of basic usage

    import tigermaster from 'fdtigermaster-admin-sdk';
    const skill = tigermaster.service.Skill;
    //upload
    const file = input.file[0];
    await skill.upload(file);
    //download
    const data = skill.download();// return blob data
  • WorkingCategory

    You can use WorkingCategory component to creat, update and get signal WorkingCategory.

    import tigermaster from 'fdtigermaster-admin-sdk';
    const workingCategory = tigermaster.services.WorkingCategory;
    //create skill
    await workingCategory.create({
        id: "TM-X01011",
        description: "單一處水管不通"
        maxPrice: 3000,
        minPrice: 1000,
        maxPricePercentage: 10,
        minPricePercentage: 70,
        priceRangeDescription: "價格描述",
        consumerWarrantyDay: 31,
        commercialWarrantyDay: 7,
        warrantyDescription: "保固描述"
    });
    //create skill
    await workingCategory.update({
        id: "TM-X01011",
        active: 0
    });
    //get skill item by it
    conse category = await workingCategory.get("TM-X01011");
  • WorkingCategory batch upload and download

    In workingCategory componemt, you can also upload and download csv formatted workingCategory config file, the following is example of basic usage

    import tigermaster from 'fdtigermaster-admin-sdk';
    const workingCategory = tigermaster.services.WorkingCategory;
    //upload
    const file = input.file[0];
    await workingCategory.upload(file);
    //download
    const data = workingCategory.download();// return blob data

Note

Note component provide method to create update and delete note for user and order, the following is the example to get Note instance.

import tigermaster from 'fdtigermaster-admin-sdk';
const note = tigermaster.note;
  • Create note

    There have two type of note you can create - user and order, and each note can have different use for option, you can create both by call

    const note = tigermaster.note;
    //create user note
    const noteId = await note.createUserNote("2020121700000", "note", note.UseFor.Normal);
    //create order note
    const noteId = await note.createOrderNote("1", "note", note.UseFor.Normal);
  • Update note

    You can update the note by noteId.

    const note = tigermaster.note;
    await note.update("1", "note");
  • Delete note

    You can delete the note by noteId.

    const note = tigermaster.note;
    await note.delete("1");
  • List by

    You can list notes by orderId and userId.

    const note = tigermaster.note;
    //list note by user
    const data = await note.listByUserId("2020121700000");
    //list note by order
    const data = await note.listByOrderId("1");
  • Get single note

    const note = tigermaster.note;
    const data = await note.getByNoteId("1");

Order

Order component provide method to create and get, the following is the example to get Order instance.

import tigermaster from 'fdtigermaster-admin-sdk';
const order = tigermaster.order;
  • Create order

    You can create order like following example.

    import tigermaster from 'fdtigermaster-admin-sdk';
    const order = tigermaster.order;
    const orderId = await order.create({
        addressCity: '臺北市',
        addressArea: '南港區',
        addressStreet: '園區街',
        addressDetail: '3-2號9樓902室',
        workingCategoryId: 'TM-X010101',
        clientUserId: '2021011700001'
    });
  • Get order

    You can get order like following example.

    import tigermaster from 'fdtigermaster-admin-sdk';
    const order = await order.get('CO2021011700001');
    console.log(order.id)// CO2021011700001
    console.log(order.data)// data of the order
  • Upload order image

    import tigermaster from 'fdtigermaster-admin-sdk';
    const order = await order.get('CO2021011700001');
    const file = input.file[0];
    const imageId = await order.imageUpload('orderId', file, '1', 'pictureDesc');

Chatroom

Chatroom component provide method to create, get, query and send from or to the chatroom, the following is the example to get Order instance.

import tigermaster from 'fdtigermaster-admin-sdk';
const chatroom = tigermaster.chatroom;
  • Create chatroom

    In the most case, all chatroom will be created by the system automatically, It's unlikely the you need to create by yourself, but it is still good to have a way to create it

    import tigermaster from 'fdtigermaster-admin-sdk';
    const chatroom = tigermaster.chatroom.create(['memberUserId1', 'memberUserId2']);
  • Get a chatroom

    You need to get a chatroom first to send and query message

    import tigermaster from 'fdtigermaster-admin-sdk';
    const chatroom = tigermaster.chatroom.get('chatroomId');
    console.log(chatroom.id)
    console.log(chatroom.userIds)
    console.log(chatroom.status)// 1=active, 0=archived
  • Send text or image to chatroom

    import tigermaster from 'fdtigermaster-admin-sdk';
    const chatroom = tigermaster.chatroom.get('chatroomId');
    await chatroom.sendText('this is a text message!');
    const file = input.file[0];
    await chatroom.sendImage(file);
  • Query and shadow query chatroom

    As an admin, you can use query to get message in a chatroom, or use shadow query to get message in a chatroom without mark the message as readed. The input of both method is a timestamp in yyyy-MM-dd HH:mm:ss fotmat and a limit (default is 50), it will query last ${limit}th newest message before ${timestamp} and sort the result in timestamp ASC order.

    Note: date-fns package is useful to construct timestamp.

    import { format } from 'date-fns';
    import tigermaster from 'fdtigermaster-admin-sdk';
    const chatroom = tigermaster.chatroom.get('chatroomId');
    const result = await chatroom.query(format(Date.now(), 'yyyy-MM-dd HH:mm:ss'));
    // const result = await chatroom.shadowQuery(format(Date.now(), 'yyyy-MM-dd HH:mm:ss')); use shadow query
    console.log(result.totalMessages) // total number of message in the chatroom
    console.log(result.queryMessages) // total number of message return in this query
    console.log(result.messages) // list message data
1.1.0

1 year ago