{"id":16482458,"url":"https://github.com/f/pq","last_synced_at":"2025-03-16T18:31:40.379Z","repository":{"id":57329293,"uuid":"61070870","full_name":"f/pq","owner":"f","description":"Human Readable Promise Chains","archived":false,"fork":false,"pushed_at":"2017-01-18T11:24:54.000Z","size":30,"stargazers_count":143,"open_issues_count":0,"forks_count":3,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-02-27T12:09:00.293Z","etag":null,"topics":["javascript","promise"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/f.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2016-06-13T21:26:35.000Z","updated_at":"2025-02-16T15:57:05.000Z","dependencies_parsed_at":"2022-08-31T00:01:28.260Z","dependency_job_id":null,"html_url":"https://github.com/f/pq","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/f%2Fpq","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/f%2Fpq/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/f%2Fpq/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/f%2Fpq/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/f","download_url":"https://codeload.github.com/f/pq/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243826788,"owners_count":20354220,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","promise"],"created_at":"2024-10-11T13:10:47.704Z","updated_at":"2025-03-16T18:31:39.890Z","avatar_url":"https://github.com/f.png","language":"JavaScript","readme":"# PQ: Human Readable Promise Chain Query Compiler\n\nPromises are awesome. But when it comes to write promise chains, it becomes kind of hard to write.\nPQ solves this issue and allows you to create **human readable promise chains**\n\n[![npm version](https://badge.fury.io/js/pquery.svg)](https://badge.fury.io/js/pquery)\n[![Build Status](https://travis-ci.org/f/pq.svg?branch=master)](https://travis-ci.org/f/pq)\n\n- Make your Promises more human-readable.\n- Allows to **create your own DSL**.\n- Zero-dependency.\n\n\u003e `pq.debug()` gives you a cool debugger to debug your queries\n\n## Install\n\nYou can simply use NPM/Bower to download **pq**.\n\n```\n# Using NPM\nnpm install pquery --save\n\n# Using Bower\nbower install pquery --save\n```\n\n## Overview\n\n**What you write:**\n```js\npq(\"(name, surname) of users of @json of #fetch('/users')\").then(...)\n\n// or more functional\npq(fetch(\"/users\"), \"(name, surname) of users of @json\").then(...)\n\n// or Unix way\npq(\"#fetch('/users') | @json | users | (name, surname)\").then(...)\n\n// or reverse pipeline\npq(\"(name, surname) \u003c| users \u003c| @json \u003c| #fetch('/users')\").then(...)\n```\n\n**This is actually what you run:**\n```js\nfetch(\"/users\").\n  then(function (response) {\n    return response.json()\n  }).\n  then(function (response) {\n    return response.users\n  }).\n  then(function (response) {\n    return response.map(function (object) { return {\n      name: object.name,\n      surname: object.surname\n  }})\n})\n```\n\n## Why?\n\nI use promises in many cases in my daily work. And **calling a promise chain** is a bit *boring* to write. I used to write `then` keyword *again and again* to create a chain and this drive me crazy, **they seem ugly**.\n\nSo, I created **pq** to make this chains **easier to write and easier to read**.\n\nLet's checkout a real-world promise example:\n```js\nvar foo = fetch(\"/hello\")\n\nfoo.then(function (response) {\n  return response.json()\n}).then(function (response) {\n  return response.data\n}) // this then's may go to the sky, or the hell!\n```\n\nThis is how to write this using **pq**:\n```js\npq(foo, \"data of @json\")\n```\n\n### Queries are Powerful Strings\n\nSince **pq** is just a string, you can create queries anywhere you want and these **may be handy to write your own DSL**. Here is a real-world example:\n\n**Instead of** writing this promise chain:\n```js\nfastfood().\nthen(function (response) {\n  return response.menus\n}).\nthen(function (response) {\n  return response.find({name: 'hamburger'})\n}).\nthen(function (response) {\n  return response.items()\n}).\nthen(function (response) {\n  return response.map(function (res) {\n    return {\n      name: res.name,\n      price: res.price\n    }\n  })\n}).\nthen(function (response) {\n  $(\"ul\").append($(\"\u003cli/\u003e\").html(`${response.name} ${response.price}`))\n})\n```\n\n**Just write this**:\n```html\n\u003cul data-pq=\"(name, price) of @items of find({name: 'hamburger'}) of menus\"\u003e\n  {% $data.forEach(function (item) { %}\n  \u003cli\u003e {{ item.name }} costs {{ item.price }} \u003c/li\u003e\n  {% }) %}\n\u003c/ul\u003e\n```\n\n## How to Write Queries\n\nThere are few simple rules to write a readable query:\n\n### Promise Chain Keywords\n\n**`then` and `of` are main keywords** to generate promise chains. `foo then bar` is actually `foo.then(function (r) { return r.bar })`. Since they are chained, the left part of chain must have the right of the chain.\n\n**`of` (reverse promise keyword) makes the query more readable. Just like the *SQL*, you define what you want at first.** `bar of foo` is `foo.then(function (r) { return r.bar })`, too.\n\nKeyword | Description | Example\n--- | --- | ---\n`.. then ` or `.. -\u003e ..` or `|\u003e` or ` | ` | Simple promise chain | `@json then data`, `@json -\u003e data`\n`.. of ..` or `.. \u003c- ..` or `\u003c|` | Simple promise chain, reversed | `data of @json`, `data \u003c- @json`\n\n\u003e You can use `of` and `then` together: `full_name of user then last_letter of first_name`.\n\u003e This will be run like: `(full_name of user) then (last_letter of first_name)`,\n\u003e which is actually `user then full_name then first_name then last_letter`.\n\n\u003e **If it becomes confusing to you, do not use them together**\n\n### Meta Characters (Optional)\n\nMeta characters are optional. But they want to make your query easier to read/write. If you want to call a function, you can just put a `@` character beginning of it. `@json` will be converted to `json()`.\n\nThe most useful meta character is `%{number}`. It allows you to pass arguments to the `pq`. `(\"a of %1\", \"b\")` will be `a of b`.\n\nCharacter | Description | Example | Equivalent\n--- | --- | --- | ---\n`@` | Method Calling | `@methodName` | `methodName()`\n`%{number}` | Simple Parameters | `pq(promise, \"%1 of @json\", \"hello\")` | `pq(promise, \"hello of @json\")`\n`\u0026` | This Object | `\u0026.length of users of @json` | `this.length of users of json()`\n`#` | Single Call | `@json of #fetch(...)` |\n`!` | Promisify | `response of !functionWithCallback` |\n\n### Tutorial\n\nThis is a simple, delayed Promised function:\n```js\nfunction sauces(id) {\n  return function () {\n    return new Promise(function (resolve) {\n      return resolve({\n        items: id == 1 ? [\n          {name: \"Ketchup\"},\n          {name: \"Mustard\"}\n        ] : [\n          {name: \"BBQ\"},\n          {name: \"Mayonnaise\"}\n        ]\n      })\n    })\n  }\n}\n\nfunction burgers() {\n  return new Promise(function (resolve) {\n    setTimeout(function () {\n      return resolve({\n        items: [\n          {name: \"McChicken\", price: \"$10\", sauces: sauces(1)},\n          {name: \"Big Mac\", price: \"$15\", sauces: sauces(2)},\n        ]\n      })\n    }, 1000)\n  })\n}\n```\n\nLet's query this using **pq**:\n\n```js\npq(burgers(), \"(price) of items\").then(function (prices) {\n  console.log(prices) // [{price: \"$10\", price: \"$15\"}]\n})\n```\n\nLet's make it more complex:\n```js\npq(burgers(), \"(name) of items of @sauces of items[0]\").then(function (sauce) {\n  console.log(sauce) // [{name: \"Ketchup\"}, {name: \"Mustard\"}]\n})\n```\n\n## How to Write Custom Parsers\n\nIt's too easy to add custom parsers using `pq.parse` command:\n\n```js\npq.parse(function (query) {\n  return query.replace(/^gh\\:([^\\s]+)/, \"#fetch('https://api.github.com/$1?page=1\u0026per_page=100')\")\n})\n\npq.parse(function (query) {\n  return query.replace(/([^\\s]+)\\s*~=\\s*([^\\s]+)/, \"filter(function (n) {return n.$1 == '$2'})\")\n})\n```\n\nThen you'll be able to use your custom parsers.\n```js\npq(\"name~=delorean of @json of gh:users/f/repos\").then(function (result) {\n  console.log(result)\n})\n```\n\n## Query Reducers\n\nQuery reducers helps you to manage your data flow easier.\n\n### `pq.before`\n\n`pq.before` will give you the raw query so you can make changes on it on-the-fly.\n\n```js\npq.before(function (query) {\n  // You can change query before compilation\n  return query\n})\n```\n\n### `pq.after`\n\n`pq.after` will give you compiled promise fragments.\n\n```js\npq.after(function (queries) {\n  // You can change queries after it's compiled\n  return queries.push(pq.compile_fragment(\"@json\"))\n})\n```\n\n## License\n\nMIT Licensed - Copyright \u0026copy; 2016 by Fatih Kadir Akın\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ff%2Fpq","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ff%2Fpq","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ff%2Fpq/lists"}