用一个对象复原 graphql语句

·  阅读 343
用一个对象复原 graphql语句

展示一个GraphQL语句

观察:对比语句和执行结果

你可以通过这段代码看出包含了查询?分页?排序?重命名等的功能吗

image.png

相关功能关键词

  • 分页 offset limit
  • 重命名 fullName: full_name
  • 查询 where and
  • 排序 order_by

预计传参

const getSpuHQL = (params: any) => {
  const { current, pageSize, noPageSize, id } = params;
  const searchKey = [
    { key: 'id', type: 'eq', value: id },
    { key: 'status', sort: 'desc' },
    { key: 'title' },
    {
      key: 'brand',
      child: [
        { key: 'id' },
        { key: 'fullName' },
        {
          key: 'company',
          child: [{ key: 'id' }, { key: 'fullName' }]
        }]
    }
  ];
  return getGql(
    'spus',
    searchKey,
    noPageSize ? undefined : { current, pageSize },
  );
};
复制代码

方法封装

分页

offset: 0 limit: 5
复制代码

计算规则

  • offset = page * limit
  • limit 是每页要请求多少条

offset limit 封装

// 默认分页规则
enum PageEnum {
  current = 1,
  pageSize = 10
}
// 分页类型
type PageInfoType = {
  current: number | undefined;
  pageSize: number | undefined;
};
/**
 * 获取分页字符串
 * @param pageInfo
 * @returns
 */
export const getPageLimit = (pageInfo?: PageInfoType) => {
  return pageInfo
    ? `offset:${
        ((pageInfo?.current || PageEnum.current) - 1) * (pageInfo?.pageSize || PageEnum.pageSize)
      },limit: ${pageInfo?.pageSize || PageEnum.pageSize},`
    : '';
};
复制代码

查询和重命名

寻找规律

  • where and 语法不变
  • 变化的是
    • 查询关键字:type、deleted_at
    • 查询类型:eq、is_null
    • 值:guess、true
where: {and: {type: {eq: "guess"}, deleted_at: {is_null: true}}}
复制代码

where and封装

export declare type WhereGqlType =
  | 'contained_in'
  | 'contains'
  | 'eq'
  | 'equals'
  | 'greater_or_equals'
  | 'greater_than'
  | 'gt'
  | 'gte'
  | 'has_key'
  | 'has_key_all'
  | 'has_key_any'
  | 'ilike'
  | 'in'
  | 'iregex'
  | 'is_null'
  | 'lesser_or_equals'
  | 'lesser_than'
  | 'like'
  | 'lt'
  | 'lte'
  | 'neq'
  | 'nilike'
  | 'nin'
  | 'niregex'
  | 'nlike'
  | 'not_equals'
  | 'not_ilike'
  | 'not_in'
  | 'not_iregex'
  | 'not_like'
  | 'not_regex'
  | 'not_similar'
  | 'nregex'
  | 'nsimilar'
  | 'regex'
  | 'similar';
  
// 查询参数  
export type WhereType = {
  key?: any;
  value?: any;
  type?: WhereGqlType;
}; 
// 下划线转换驼峰
function toHump(name: string) {
  return name.replace(/_(\w)/g, function (all, letter) {
    return letter.toUpperCase();
  });
}
// 驼峰转换下划线
function toLine(name: string) {
  return name.replace(/([A-Z])/g, '_$1').toLowerCase();
}
// 拼接where多个或者单个
const getWhereDetail = (item: WhereType) => {
  let valueStr = `"${item.value}"`;
  if (Object.prototype.toString.call(item.value) === '[object Array]') {
    valueStr = JSON.stringify(item.value);
  }
  return `{${item.type}:${valueStr}},`;
};

/**
 * 获取where查询云集
 * @param obj 查询对象信息
 * @returns
 */
export const getWhereStr = (lists: WhereType[]) => {
  const list = lists.filter((item) => item.value || item.value === false);
  let str = '';
  if (list.length > 0) {
    str += `where:{and:{`;// 固定结构
    str += list.map((item) => `${toLine(item.key)}:${getWhereDetail(item)}`).join('');// 重命名
    str += `}}`;// 固定结构
  }
  return str;
};
复制代码

排序

寻找规律

  • where and 语法不变
  • 变化的是
    • 排序关键字:status、recommend
    • 查询类型:desc、asc

order 封装

export declare type OrderGqlType = 'desc' | 'asc';
type OrderType = {
  key?: any;
  sort?: OrderGqlType;
};
/**
 * 获取order查询云集
 * @param obj 查询对象信息
 * @returns
 */
export const getOrderStr = (list: OrderType[]) => {
  let str = '';
  if (list.length > 0) {
    str += `order_by:{`;
    str += list.map((item) => `${toLine(item.key)}:${item.sort}`).join(',');
    str += `}`;
  }
  return str;
};
复制代码

基础查询字段拼接

/**
 * 获取查询Keys的字符串
 * @param searchKeys 查询的key
 * @returns
 */
export const searchKeyFormat = (searchKeys: string[]) => {
  let str = '';
  str += searchKeys
    .map((item) => {
      if (item.search('{') !== -1 && item.search('}') !== -1) {
        return ` ${item}`;
      }
      return ` ${item}:${toLine(item)}`;
    })
    .join('\n');
  return str;
};
复制代码

分页查询排序逻辑处理

export const tableFunc = (where: string, pageInfo?: PageInfoType, orderList?: any) => {
  const limitStr = `${getPageLimit(pageInfo)}`;
  const orderStr = getOrderStr(orderList || []);
  let func = '';
  if ((where && pageInfo) || (where && orderStr) || (limitStr && orderStr)) {
    func = `(${limitStr}${where ? `${where},` : ''}${orderStr})`;
  } else if (where) {
    func = `(${where})`;
  } else if (pageInfo) {
    func = `(${limitStr})`;
  } else if (orderList) {
    func = `(${orderStr})`;
  }
  return func;
};

复制代码

查询结构封装

/**
 * 获取查询Keys的字符串
 * @param searchKeys 查询的key
 * @returns
 */
export const searchKeyFormat = (searchKeys: string[]) => {
  let str = '';
  str += searchKeys
    .map((item) => {
      return `${item}:${toLine(item)}`;
    })
    .join('\n');
  return str;
};
// 递归获取查询字符串
function getStr(searchKeys: SearchItemType[]): string {
  const str = searchKeys.map(one => {
    if (one.child) {
      return `${one.key}{${getStr(one.child)}}`
    }
    return searchKeyFormat([one.key])
  })
  return `${str.join('\n')}`
}
复制代码

获取查询语句


/**
 * 查询方法
 * @param  tableName 表名称
 * @param searchKeys 需要查询查询字段的keys
 * @param where 查询条件
 * @returns
 */

export const getGql = (
  tableName: string,
  searchKeys: SearchItemType[],
  pageInfo?: PageInfoType | undefined,
) => {
  const whereList = searchKeys.filter(one => one.type)
  const orderList = searchKeys.filter(one => one.sort)
  const where = getWhereStr(whereList || []);
  const tableFuncStr = `${tableName}${tableFunc(where, pageInfo, orderList)}`;
  const gql = `
  {
    page:${`${tableName}${where ? `(${where})` : ''}`}{
      total:count_id
    }
    ${tableFuncStr}{
      ${getStr(searchKeys)}
    }
  }
`;
  return gql;
};
复制代码
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改