POSTG+REST

学习了一下PostgREST,我觉得这古怪的东西早该出现了。多少2B业务都在上Java全家桶,就我的浅见,一般框架的服务层都几乎可以杀掉,大多数只起转发作用。PGREST在某种程度代表了左派的观念,消灭臃肿的后端。

照惯例说一下安装配置。官网直接下载二进制执行文件,直接./postgrest就可以运行了。通过–help看看配置条款,自己看需要配置什么,比如:

//main.conf
db-uri = "postgres://fat:password@localhost/api"
db-schema = "public"
db-anon-role = "fat"
server-port = 3001

pgrest默认端口也是3000,我一般用来起Nodejs,所以加了1位。在相对位置建张表,写条数据:

create table word(id serial primary key, 
    word varchar not null unique, 
    tags varchar[], explanations text);
insert into word(word, tags, explanations) 
    values('ok', ARRAY['adj'], '好‘)

现在./postgrest main.conf,在前端访问localhost:3001/word,会返回:

[{"id":1,"word":"good","tags":["adj"],"explanations":"好"}]

是不是非常简单?还可以试试推数据:

curl http://localhost:3001/word -X POST 
    -H "Content-Type: application/json" 
    -d '{"word": "bad", "tags":["adj", "adv"], "explanations":"坏"}'

返回200说明推成功。前端现在会返回:

[{"id":1,"word":"good","tags":["adj"],"explanations":"好"}, 
 {"id":2,"word":"bad","tags":["adj","adv"],"explanations":"坏"}]

我觉得主要是PG支持数组,这为JSON化数据提供了相当大的便利。

PGR的查询可以解析子命令,举个例子:

get http://localhost:3001/word?tags=cs.{adv} //cs = contains
// [{"id":2,"word":"bad","tags":["adj","adv"],"explanations":"坏"}]

get http://localhost:3001/word?select=word,explanations&id=gt.1 
// [{"word":"bad","explanations":"坏"}]

还是很简单。接着再创建一张新表。原表添加一些内容:

create table category (id serial primary key, 
    name varchar not null);
alter table word add column category_id int;
alter table word add constraint FK_Category 
    foreign key (CategoryID) references category(id);
insert into category (name) values('something');

也就是加了外键。PGR可以自动链接查询…也就是说:

http://localhost:3001/word?select=word,explanations,category(name)
// [{"word":"good","explanations":"好",
//   "category":{"name":"something"}}, 
// {"word":"bad","explanations":"坏",
//   "category":{"name":"something"}}]

P.S. 需要重启服务端

PGR内部已经做好了ORM,怒赞。话说回来PostgREST都做成这样了,还要啥自行车?

还有更多有趣细节,可以浏览一下文档呐。

This entry was posted in 杂物间 and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *