normalizr ​​​​​​​ 数据格式化 规范数据接口

原文链接: normalizr 数据格式化 规范数据接口

上一篇: c++11 异步多线程优化fib 使用 future和async

下一篇: ts 装饰器

参考

https://zhuanlan.zhihu.com/p/36487766

https://github.com/paularmstrong/normalizr

https://developer.aliyun.com/article/3168

安装

yarn add normalizr

npm install normalizr

简单使用

其实就是对数据进行了转换, 使得在使用过程中更加便利

up-ddac01122ca40ef9780af0814bf52e46d83.png

const { normalize, schema } = require("normalizr");
const originalData = {
  id: "123",
  author: {
    id: "1",
    name: "Paul",
  },
  title: "My awesome blog post",
  comments: [
    {
      id: "324",
      commenter: {
        id: "2",
        name: "Nicole",
      },
    },
  ],
};
// Define a users schema
const user = new schema.Entity("users");

// Define your comments schema
const comment = new schema.Entity("comments", {
  commenter: user,
});

// Define your article
const article = new schema.Entity("articles", {
  author: user,
  comments: [comment],
});

const normalizedData = normalize(originalData, article);
console.log(normalizedData);

反解析? 好像用的比较少... 在github测试文件中才找到的

const { schema, denormalize } = require("normalizr");

const user = new schema.Entity("users");
const comment = new schema.Entity("comments", {
  user: user,
});
const article = new schema.Entity("articles", {
  author: user,
  comments: [comment],
});

const entities = {
  articles: {
    "123": {
      author: "8472",
      body: "This article is great.",
      comments: ["comment-123-4738"],
      id: "123",
      title: "A Great Article",
    },
  },
  comments: {
    "comment-123-4738": {
      comment: "I like it!",
      id: "comment-123-4738",
      user: "10293",
    },
  },
  users: {
    "10293": {
      id: "10293",
      name: "Jane",
    },
    "8472": {
      id: "8472",
      name: "Paul",
    },
  },
};

const denormalizedData = denormalize("123", article, entities);
const out2 = JSON.stringify(denormalizedData, null, 2);
console.log(out2);
/*
{
  "author": {
    "id": "8472",
    "name": "Paul"
  },
  "body": "This article is great.",
  "comments": [
    {
      "comment": "I like it!",
      "id": "comment-123-4738",
      "user": {
        "id": "10293",
        "name": "Jane"
      }
    }
  ],
  "id": "123",
  "title": "A Great Article"
}


*/

删除某些id, 对输出数据做限制

const { schema, normalize } = require("normalizr");

const user = new schema.Entity(
  "user",
  {},
  {
    processStrategy: (value, parent, key) => {
      console.log(value, parent, key);
      delete value.userId
      return value;
    },
  }
);
const users = new schema.Array(user);

const entities = [
  { id: 1, userId: 1, name: "a" },
  { id: 2, userId: 2, name: "b" },
  { id: 3, userId: 3, name: "c" },
];

const denormalizedData = normalize(entities, users);
const out2 = JSON.stringify(denormalizedData, null, 2);
console.log(out2);
/*
{
  "author": {
    "id": "8472",
    "name": "Paul"
  },
  "body": "This article is great.",
  "comments": [
    {
      "comment": "I like it!",
      "id": "comment-123-4738",
      "user": {
        "id": "10293",
        "name": "Jane"
      }
    }
  ],
  "id": "123",
  "title": "A Great Article"
}


*/

递归的数据结构

up-2e606b9f00d8959c3d5cfce2b53261c6c1f.png

const fs = require("fs");
const { normalize, schema } = require("normalizr");
const s = fs.readFileSync("./in.json", "utf8");
const originalData = JSON.parse(s);
const user = new schema.Entity("users");

user.define({
  parent: user,
});

const normalizedData = normalize(originalData, user);
const out = JSON.stringify(normalizedData, null, 2);
fs.writeFileSync("./out.json", out, "utf8");
console.log(out);
{
  "id": 1,
  "name": "Andy Warhol",
  "parent": {
    "id": 7,
    "name": "Tom Dale",
    "parent": {
      "id": 4,
      "name": "Pete Hunt"
    }
  }
}

简单数组转换

up-7c68dc0709999f57660613eda7611d1419a.png

const fs = require("fs");
const { normalize, schema } = require("normalizr");
const list = [
  {
    id: 1,
    title: "Some Article",
    author: {
      id: 1,
      name: "Dan",
    },
  },
  {
    id: 2,
    title: "Other Article",
    author: {
      id: 1,
      name: "Dan",
    },
  },
];
const article = new schema.Entity("articles");
const users = new schema.Entity("users");
const collection = new schema.Entity("collections");
article.define({
  author: users,
});
collection.define({
  curator: users,
});

const articleList = new schema.Array(article);
const normalizedData = normalize(list, articleList);
const out = JSON.stringify(normalizedData, null, 2);
fs.writeFileSync("./out.json", out, "utf8");
console.log(out);

复杂数组

up-1a984ca80ac56f6475cca541ee9482704cc.png

const fs = require("fs");
const { normalize, schema, Array } = require("normalizr");
const s = fs.readFileSync("./in.json", "utf8");
const originalData = JSON.parse(s);
const store = new schema.Entity("store", {}, { idAttribute: "sortName" });
const area = new schema.Entity("area", {
  stores: [store],
});
const normalizedData = normalize(originalData, new schema.Array(area));
const out = JSON.stringify(normalizedData, null, 2);
fs.writeFileSync("./out.json", out, "utf8");
console.log(out);
[
  {
    "id": "CABA",
    "area": "Ciudad Autónoma de Buenos Aires",
    "stores": [
      {
        "name": "ABASTO",
        "sortName": "AB"
      },
      {
        "name": "MICRO-CENTRO",
        "sortName": "MC"
      },
      {
        "name": "CABALLITO",
        "sortName": "CB"
      },
      {
        "name": "BELGRANO",
        "sortName": "BE"
      }
    ]
  },
  {
    "id": "BSAS",
    "area": "Provincia de Buenos Aires",
    "stores": [
      {
        "name": "RAMOS MEJIA",
        "sortName": "RM"
      },
      {
        "name": "LANUS",
        "sortName": "LN"
      },
      {
        "name": "LA PLATA",
        "sortName": "LP"
      },
      {
        "name": "VICENTE LOPEZ",
        "sortName": "VL"
      }
    ]
  },
  {
    "id": "Interior",
    "area": "Interior del País",
    "stores": [
      {
        "name": "ROSARIO",
        "sortName": "RO"
      },
      {
        "name": "CORDOBA",
        "sortName": "CO"
      }
    ]
  }
]

博客数据的转换

up-a4c7f3ba6c531db1ab58c6186d4f182b163.png

const fs = require("fs");
const { normalize, schema, Array } = require("normalizr");
const s = fs.readFileSync("./in.json", "utf8");
const originalData = JSON.parse(s);

const postSchema = new schema.Entity('posts', { idAttribute: 'id' });
const postAuthorSchema = new schema.Entity('postAuthors', { idAttribute: 'id' });
const commentSchema = new schema.Entity('comments', { idAttribute: 'id' });
const commentAuthorSchema = new schema.Entity('commentAuthors', { idAttribute: 'id' });

postSchema.define({
  author: postAuthorSchema,
  comments: new schema.Array(commentSchema)
});

//comment嵌套的author提取出来'commentAuthors'
commentSchema.define({
  author: commentAuthorSchema
});


const normalizedData = normalize(originalData, postSchema);
const out = JSON.stringify(normalizedData, null, 2);
fs.writeFileSync("./out.json", out, "utf8");
console.log(out);
const fs = require("fs");
const { normalize, schema, Array } = require("normalizr");
const s = fs.readFileSync("./in.json", "utf8");
const originalData = JSON.parse(s);

const postSchema = new schema.Entity('posts', { idAttribute: 'id' });
const postAuthorSchema = new schema.Entity('postAuthors', { idAttribute: 'id' });
const commentSchema = new schema.Entity('comments', { idAttribute: 'id' });
const commentAuthorSchema = new schema.Entity('commentAuthors', { idAttribute: 'id' });

postSchema.define({
  author: postAuthorSchema,
  comments: new schema.Array(commentSchema)
});

//comment嵌套的author提取出来'commentAuthors'
commentSchema.define({
  author: commentAuthorSchema
});


const normalizedData = normalize(originalData, postSchema);
const out = JSON.stringify(normalizedData, null, 2);
fs.writeFileSync("./out.json", out, "utf8");
console.log(out);

转换对象

up-1b7072fb49c9557fea824b3142a28f07d97.png

const { normalize, schema } = require("normalizr");
const fs = require("fs");

// assignEntity删除后端返回额外数据的
const options = {
  processStrategy: function (obj, key, val) {
    console.log("-====");
    obj[key] = val;
    delete obj[key + "Id"];
  },
};

const article = new schema.Entity("articles");
const type = new schema.Entity("types", options);

// 定义内嵌规则
article.define({
  type: type,
});

const originalData = {
  id: 1,
  name: "wang",
  subject: [
    {
      id: 11,
      name: "语文",
      score: [
        {
          id: 111,
          期中: "80",
        },
        {
          id: 112,
          期末: "90",
        },
      ],
    },
    {
      id: 12,
      name: "数学",
      score: [
        {
          id: 113,
          期中: "80",
        },
        {
          id: 114,
          期末: "90",
        },
      ],
    },
  ],
};

const scoreSchema = new schema.Entity("score");
const newScore = [scoreSchema];

const subjectSchema = new schema.Entity("subject", {
  score: newScore,
});
const newSubject = [subjectSchema];

const dataSchema = {
  subject: newSubject,
};

const normalizedData = normalize(originalData, dataSchema);
const out = JSON.stringify(normalizedData, null, 2);
fs.writeFileSync("./out.json", out, "utf8");
console.log(out);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值