4.2.4 框架之网络请求-HttpClient

oinone提供统一的网络请求底座,基于graphql二次封装

一、初始化

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setMiddleware() // 必须设置,请求回调。具体查看文章https://shushi.yuque.com/yqitvf/oinone/vwo80g
http.setBaseURL() // 必须设置,后端请求的路径

图4-2-4-1 初始化代码示例

二、HttpClient详细介绍

获取实例

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();

图4-2-4-2 获取实例

接口地址

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setBaseURL('接口地址');
http.getBaseURL(); // 获取接口地址

图4-2-4-3 接口地址

请求头

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setHeader({key: value});

图4-2-4-4 请求头

variables

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setExtendVariables((moduleName: string) => {
 return customFuntion();

});

图4-2-4-5 variables

回调

import { HttpClient } from '@kunlun/dependencies';
const http = HttpClient.getInstance();
http.setMiddleware([middleware]);

图4-2-4-6 回调

业务使用-query

private http = HttpClient.getInstance();
private getTestQuery = async () => {
 const query = `gql str`;
 const result = await this.http.query('module name', query);
 console.log(result)
 return result.data[`xx`]['xx']; // 返回的接口,打印出result对象层次返回
};

图4-2-4-7 业务使用-query

业务使用-mutate

private http = HttpClient.getInstance();

private getTestMutate = async () => {
  const mutation = `gql str`;

  const result = await this.http.mutate('module name', mutation);
    console.log(result)
  return result.data[`xx`]['xx']; // 返回的接口,打印出result对象层次返回
};

图4-2-4-8 业务使用-mutate

三、如何使用HttpClient

初始化

在项目目录src/main.ts下初始化httpClient

初始化必须要做的事:

  • 设置服务接口链接

  • 设置接口请求回调

业务实战

前文说到自定义新增宠物表单,让我们在这个基础上加入我们的httpClient;

第一步新增service.ts

image.png

图4-2-4-8 新增service.ts

service.ts

import { HttpClient } from '@kunlun/dependencies';

const addPetMutate = async (modelName, data) => {
    const http = HttpClient.getInstance();
    const mutateGql = `mutation{
    petMutation{
      addPet(data:${data})
       {
        id
      }
    }
  }`;

    const result = await http.mutate('pet', mutateGql);
    return (result as any).data['petMutation']['addPet'];
};

export { addPetMutate };

图4-2-4-9 service.ts

第二步业务中使用

import { constructOne, queryOne, SPI, ViewWidget, Widget, IModel, getModelByUrl, getModel, getIdByUrl, FormWidgetV3, CustomWidget, CallChaining } from '@kunlun/dependencies';
import PetFormView from './PetFormView.vue';
// 引入
import { addPetMutate } from './service';

@SPI.ClassFactory(CustomWidget.Token({ widget: 'PetForm' }))
export class PetFormViewWidget extends FormWidgetV3 {
  public initialize(props) {
    super.initialize(props);
    this.setComponent(PetFormView);
    return this;
  }

  /**
   * 数据提交
   * @protected
   */
  @Widget.Reactive()
  @Widget.Inject()
  protected callChaining: CallChaining | undefined;

  private modelInstance!: IModel;

  /**
   * 重要!!!!
   * 当字段改变时修改formData
   * */
  @Widget.Method()
  public onFieldChange(fieldName: string, value) {
    this.setDataByKey(fieldName, value);
  }

  /**
   * 表单编辑时查询数据
   * */
  public async fetchData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {
    this.setBusy(true);
    const context: typeof options = { sourceModel: this.modelInstance.model, ...options };
    const fields = this.modelInstance?.modelFields;
    try {
      const id = getIdByUrl();
      const data = (await queryOne(this.modelInstance.model, (content[0] || { id }) as Record<string, string>, fields, variables, context)) as Record<string, unknown>;

      this.loadData(data);
      this.setBusy(false);
      return data;
    } catch (e) {
      console.error(e);
    } finally {
      this.setBusy(false);
    }
  }

  /**
   * 新增数据时获取表单默认值
   * */
  @Widget.Method()
  public async constructData(content: Record<string, unknown>[] = [], options: Record<string, unknown> = {}, variables: Record<string, unknown> = {}) {
    this.setBusy(true);
    const context: typeof options = { sourceModel: this.modelInstance.model, ...options };
    const fields = this.modelInstance.modelFields;
    const reqData = content[0] || {};
    const data = await constructOne(this.modelInstance!.model, reqData, fields, variables, context);
    return data as Record<string, unknown>;
  }

  @Widget.Method()
  private async reloadData() {
    const data = await this.constructData();
    // 覆盖formData
    this.setData(data);
  }

  @Widget.Method()
  public onChange(name, value) {
    this.formData[name] = value;
  }

  protected async mounted() {
    super.mounted();
    const modelModel = getModelByUrl();
    this.modelInstance = await getModel(modelModel);
    this.fetchData();
    // 数据提交钩子函数!!!
    this.callChaining?.callBefore(() => {
      return this.formData;
    });
  }

  @Widget.Method()
  private async addPet() {
    // 调用
    const data = await addPetMutate('petModule', this.getData());
  }
}

图4-2-4-10 业务中使用

Oinone社区 作者:史, 昂原创文章,如若转载,请注明出处:https://doc.oinone.top/oio4/9305.html

访问Oinone官网:https://www.oinone.top获取数式Oinone低代码应用平台体验

(0)
史, 昂的头像史, 昂数式管理员
上一篇 2024年5月23日 am8:33
下一篇 2024年5月23日 am8:35

相关推荐

  • 4.1.25 框架之搜索引擎

    一、使用场景 在碰到大数据量并且需要全文检索的场景,我们在分布式架构中基本会架设ElasticSearch来作为一个常规解决方案。在oinone体系中增强模型就是应对这类场景,其背后也是整合了ElasticSearch。 二、整体介绍 oinone与es整合设计图 图4-1-25-1 Oinone与es整合设计图 基础环境安装 Canal安装 详见4.1.10【函数之触发与定时】一文 修改Canal配置并重启 新增Canal的实例【destinaion: pamirs】,监听分表模型的binlog【filter: demo.demo_core_sharding_model……】用于增量同步 pamirs: middleware: data-source: jdbc-url: jdbc:mysql://localhost:3306/canal_tsdb?useUnicode=true&characterEncoding=utf-8&verifyServerCertificate=false&useSSL=false&requireSSL=false driver-class-name: com.mysql.cj.jdbc.Driver username: root password: oinone canal: ip: 127.0.0.1 port: 1111 metricsPort: 1112 zkClusters: – 127.0.0.1:2181 destinations: – destinaion: pamirschangedata name: pamirschangedata desc: pamirschangedata slaveId: 1235 filter: demo\.demo_core_pet_talent dbUserName: root dbPassword: oinone memoryStorageBufferSize: 65536 topic: CHANGE_DATA_EVENT_TOPIC dynamicTopic: false dbs: – { address: 127.0.0.1, port: 3306 } – destinaion: pamirs id: 1234 name: pamirs desc: pamirs slaveId: 1234 filter: demo\.demo_core_sharding_model_0,demo\.demo_core_sharding_model_1,demo\.demo_core_sharding_model_2,demo\.demo_core_sharding_model_3,demo\.demo_core_sharding_model_4,demo\.demo_core_sharding_model_5,demo\.demo_core_sharding_model_6,demo\.demo_core_sharding_model_7 dbUserName: root dbPassword: oinone memoryStorageBufferSize: 65536 topic: BINLOG_EVENT_TOPIC dynamicTopic: false dbs: – { address: 127.0.0.1, port: 3306 } tsdb: enable: true jdbcUrl: "jdbc:mysql://127.0.0.1:3306/canal_tsdb" userName: root password: oinone mq: rocketmq rocketmq: namesrv: 127.0.0.1:9876 retryTimesWhenSendFailed: 5 dubbo: application: name: canal-server version: 1.0.0 registry: address: zookeeper://127.0.0.1:2181 protocol: name: dubbo port: 20881 scan: base-packages: pro.shushi server: address: 0.0.0.0 port: 10010 sessionTimeout: 3600 图4-1-25-2 修改Canal配置并重启 ES安装 下载安装包官方下载地址,也可以直接下载elasticsearch-8.4.1-darwin-x86_64.tar.gz.txt(361.7 MB),下载后去除后缀.txt,然后解压文件 替换安装目录/config下的[elasticsearch.yml](elasticsearch)(1 KB),主要是文件中追加了三个配置 xpack.security.enabled: false xpack.security.http.ssl.enabled: false xpack.security.transport.ssl.enabled: false 图4-1-25-3 elasticsearc.yml追加三个配置 启动 a. 导入环境变量(ES运行时需要JDK18及以上版本JDK运行环境, ES安装包中包含了一个JDK18版本) # export JAVA_HOME=/Users/oinone/Documents/oinone/es/elasticsearch-8.4.1/jdk.app/Contents/Home/ export JAVA_HOME=ES解压安装目录/jdk.app/Contents/Home/ 图4-1-25-4 导入环境变量 b. 运行ES ## nohup /Users/oinone/Documents/oinone/es/elasticsearch-8.4.1/bin/elasticsearch >> $TMPDIR/elastic.log 2>&1 & nohup ES安装目录/bin/elasticsearch >> $TMPDIR/elastic.log 2>&1 & 图4-1-25-5 运行ES 停止ES lsof…

    2024年5月23日
    64000
  • 4.2.3 框架之SPI机制

    SPI(Service Provider Interface)服务提供接口,是一套用来被第三方实现或者扩展的API,它可以用来启用框架扩展和替换组件,简单来说就是用来解耦,实现组件的自由插拔,这样我们就能在平台提供的基础组件外扩展新组件或覆盖平台组件。 目前定义SPI组件 ViewWidget 视图组件 FieldWidget 字段组件 ActionWidget 动作组件 表4-2-3-1 目前定义SPI组件 前提知识点 使用 TypeScript 装饰器(注解)装饰你的代码 1. 通过注解定义一种SPI接口(Interface) @SPI.Base<IViewFilterOptions, IView>('View', ['id', 'name', 'type', 'model', 'widget']) export abstract class ViewWidget<ViewData = any> extends DslNodeWidget { } 图4-2-3-1 代码示意 2. 通过注解注册提供View类型接口的一个或多个实现 @SPI.Base<IViewFilterOptions, IView>('View', ['id', 'name', 'type', 'model', 'widget']) export abstract class ViewWidget<ViewData = any> extends DslNodeWidget { } 图4-2-3-2 代码示意 3. 视图的xml内通过配置来调用已定义的一种SPI组件 <view widget="form" model="demo.shop"> <field name="id" /> </view> 图4-2-3-3 代码示意 图4-2-3-4 组件继承示意图 当有多个服务提供方时,按以下规则匹配出最符合条件的服务提供方 SPI匹配规则 SPI组件没有严格的按匹配选项属性限定,而是一个匹配规则 按widget最优先匹配,配置了widget等于是指定了需要调用哪个widget,此时其他属性直接忽略 按最大匹配原则(匹配到的属性越多优先级越高) 按后注册优先原则

    2024年5月23日
    61300
  • 3.5.2.1 整体介绍

    虽然我们有小眼睛可以让用户自定义展示字段和排序喜好,以及通过权限控制行、列展示,但在我们日常业务开发中还是会对页面进行调整,以满足业务方的对交互友好和便捷性的要求。本节会在如何自定义之前我们先介绍页面结构与逻辑,再带小伙伴一起完成自定义view的Template和Layout,以及整个母版的Template和Layout 页面的构成讲解 页面交互拓扑图 页面交互拓扑图 图3-5-2-1 页面交互拓扑图 注:页面逻辑交互拓扑图说明 模块作为主切换入口 模块决定菜单列表 菜单切换触发点击action 前端根据Mask、View进行渲染, a. Mask是母版是确定了主题、非主内容分发区域所使用组件和主内容分发区域联动方式的页面模板。全局、应用、视图动作、视图都可以通过mask属性指定母版 bMask和View都是有layout定义和template定义合并而成,系统会提供默认母版,以及为每种视图提供默认layout c. layout与template通过插槽进行匹配 Action根据不同类型做出不同访问后端服务、url跳转、页面路由、发起客户端动作等 Aciton路由可以指定Mask、视图组件的layout、template a. 当layout没有指定的时候则用系统默认的 b. 当template没有指定的时候,且视图组件相同类型有多条记录时,根据优先级选取 Mask和视图组件的layout优先级(视图组件>视图动作 > 应用 > 全局) 默认母版以及各类视图组件 母版布局 默认母版基础布局base-layout <mask layout="default"> <header slot="header"/> <container slot="main" name="main"> <sidebar slot="sidebar"/> <container slot="content"/> </container> <footer slot="footer"/> </mask> 图3-5-2-2 默认母版基础布局base-layout 母版template <mask layout="default"> <mask name="defaultMask"> <template slot="header"> <container name="appBar"> <element widget="logo"/> <element widget="appFinder"/> </container> <container name="operationBar"> <element widget="notification"/> <element widget="dividerVertical"/> <element widget="languages"/> </container> <element widget="userProfile"/> </template> <template slot="sidebar"> <element widget="navMenu"/> </template> <template slot="content"> <element widget="breadcrumb"/> <element widget="mainView"/> </template> </mask> 图3-5-2-3 母版template 注: 上例中因为名称为main的插槽不需要设置更多的属性,所以在template中缺省了main插槽的template标签。 最终可执行视图 <mask name="defaultMask"> <header> <container name="appBar"> <element widget="logo"/> <element widget="appFinder"/> </container> <container name="operationBar"> <element widget="notification"/> <element widget="dividerVertical"/> <element widget="languages"/> </container> <element widget="userProfile"/> </header> <container name="main"> <sidebar name="sidebar"> <element widget="navMenu"/> </sidebar> <container name="content"> <element widget="breadcrumb"/> <element widget="mainView"/> </container> </container> <footer/> </mask> 图3-5-2-4 最终可执行视图 表格视图布局 默认表格视图基础布局base-layout <view type="table"> <view type="search"> <element widget="search" slot="search"> <xslot name="fields" slotSupport="field" /> </element> </view> <pack widget="fieldset"> <element widget="actionBar" slot="actions" slotSupport="action" /> <element widget="table" slot="table"> <xslot name="fields" slotSupport="field" /> <element widget="actionsColumn" slot="actionsColumn"> <xslot name="rowActions" slotSupport="action" /> </element> </element> </pack> </view> 图3-5-2-5 默认表格视图基础布局base-layout 注:table标签的子标签为column组件,如果field填充到元数据插槽fields没有column组件将自动包裹column组件。 表格视图template <view type="table" model="xxx" name="tableViewExample">…

    2024年5月23日
    78400
  • 3.5 Oinone以交互为外在

    交互组件(UI Componment): 用组件化的方式统一管理:菜单、布局、视图 用Action做衔接,来勾绘出模块的前端交互拓扑,描述所有可操作行为 oinone的页面路由串联规则是以菜单为导航,用Action做衔接,用View做展示,详见3.5.2.1View的【整体介绍】。 本章节会重点介绍: 如何定义菜单、视图、行为以及其初始化 xml配置:视图配置(包括字段联动)、字段配置、布局配置、动作配置 前端组件自定义

Leave a Reply

登录后才能评论