├── .editorconfig ├── .gitignore ├── .travis.yml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── code-of-conduct.md ├── examples ├── basic │ └── App.vue ├── with-ouvue-render-component │ ├── .eslintignore │ ├── .eslintrc.js │ ├── .gitignore │ ├── README.md │ ├── babel.config.js │ ├── package-lock.json │ ├── package.json │ ├── public │ │ ├── favicon.ico │ │ └── index.html │ └── src │ │ ├── App.vue │ │ ├── assets │ │ └── logo.png │ │ ├── components │ │ └── HelloWorld.vue │ │ ├── main.js │ │ └── services │ │ ├── index.js │ │ └── posts.js └── with-prototype-and-service-structure │ ├── App.vue │ ├── main.js │ ├── package-lock.json │ ├── package.json │ └── services │ ├── index.js │ └── posts.js ├── package-lock.json ├── package.json ├── rollup.config.ts ├── src ├── cache.ts ├── components │ └── OuvueRender.ts ├── ouvue.ts └── types │ └── index.ts ├── test ├── OuvueRender.test.ts ├── cache.test.ts └── ouvue.test.ts ├── tools ├── gh-pages-publish.ts └── semantic-release-prepare.ts ├── tsconfig.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | #root = true 2 | 3 | [*] 4 | indent_style = space 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | max_line_length = 100 10 | indent_size = 2 11 | 12 | [*.md] 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | coverage 3 | .nyc_output 4 | .DS_Store 5 | *.log 6 | .vscode 7 | .idea 8 | dist 9 | compiled 10 | .awcache 11 | .rpt2_cache 12 | docs 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | cache: 3 | directories: 4 | - ~/.npm 5 | notifications: 6 | email: false 7 | node_js: 8 | - '12' 9 | before_script: 10 | - npm install -g jest 11 | script: 12 | - npm run test:prod && npm run build 13 | after_success: 14 | - npm run travis-deploy-once "npm run report-coverage" 15 | - if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then npm run travis-deploy-once "npm run deploy-docs"; fi 16 | - if [ "$TRAVIS_BRANCH" = "master" -a "$TRAVIS_PULL_REQUEST" = "false" ]; then npm run travis-deploy-once "npm run semantic-release"; fi 17 | branches: 18 | except: 19 | - /^v\d+\.\d+\.\d+$/ 20 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We're really glad you're reading this, because we need volunteer developers to help this project come to fruition. 👏 2 | 3 | ## Instructions 4 | 5 | These steps will guide you through contributing to this project: 6 | 7 | - Fork the repo 8 | - Clone it and install dependencies 9 | 10 | git clone https://github.com/YOUR-USERNAME/typescript-library-starter 11 | npm install 12 | 13 | Keep in mind that after running `npm install` the git repo is reset. So a good way to cope with this is to have a copy of the folder to push the changes, and the other to try them. 14 | 15 | Make and commit your changes. Make sure the commands npm run build and npm run test:prod are working. 16 | 17 | Finally send a [GitHub Pull Request](https://github.com/alexjoverm/typescript-library-starter/compare?expand=1) with a clear list of what you've done (read more [about pull requests](https://help.github.com/articles/about-pull-requests/)). Make sure all of your commits are atomic (one feature per commit). 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2017 Igor Halfeld 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Ouvue 👂🏻 2 | 3 | [![Travis](https://img.shields.io/travis/IgorHalfeld/ouvue.svg)](https://travis-ci.org/IgorHalfeld/ouvue) 4 | [![Coveralls](https://img.shields.io/coveralls/alexjoverm/typescript-library-starter.svg)](https://coveralls.io/github/alexjoverm/typescript-library-starter) 5 | [![Donate](https://img.shields.io/badge/donate-picpay-green.svg)](http://picpay.me/igorhalfeld) 6 | 7 | > ⚠️ Beta version!! Do not use in production!! 8 | 9 | Simple and scalable service layer(with cache 🤩) for Vue REST clients 10 | 11 | - 🔥 Suports Vue.js 2 and 3 _(in progress on branch `next`)_ 12 | - 😙 Zero dependencies 13 | - 💅 Typescript support 14 | - 😍 Code coverage with >90% 15 | 16 | ### Install 17 | 18 | ```javascript 19 | import { create } from '@ouvue/core' 20 | ``` 21 | 22 | ### Usage 23 | 24 | ```js 25 | import { create } from '@ouvue/core' 26 | 27 | const services = { 28 | posts: { 29 | async getAll () { 30 | console.log('Getting posts...') 31 | // You don't need to put on a try/catch, Ouvue does it for you 😉 32 | const res = await window.fetch('https://jsonplaceholder.typicode.com/posts') 33 | const result = await res.json() 34 | 35 | return result 36 | } 37 | } 38 | } 39 | 40 | const api = create({ services }) 41 | 42 | export default { 43 | async mounted () { 44 | const posts = await this.getPosts() 45 | console.log('Posts', posts) 46 | 47 | window.setTimeout(async () => { 48 | console.log(await this.getPosts()) 49 | }, 2000) 50 | }, 51 | methods: { 52 | async getPosts() { 53 | return api.fetch('posts/getAll') 54 | } 55 | } 56 | } 57 | ``` 58 | 59 | See this code [live](https://ouvue-basic-vue-demo.surge.sh/) and check out [examples folder](https://github.com/IgorHalfeld/ouvue/tree/master/examples/) 60 | 61 | ### API 62 | 63 | - `create(options)` - create instance of `Ouvue` 64 | _options signature_ 65 | ```js 66 | { 67 | services, 68 | cache: { 69 | strategy: 'inmemory' // default 70 | } 71 | } 72 | ``` 73 | `create` return an object with a `fetch` function and `OuvueRender` component 74 | 75 | - `fetch(key, payload, options)` - fetch executes a service. 76 | ```js 77 | key: e.g. 'users/create' 78 | payload: e.g. { name: 'Igor' } 79 | options: e.g. { onlyNetwork: true } // if exists on cache, call the network and update the cache 80 | ``` 81 | - `` - fetch executes a service but with component-based approach 82 | ```html 83 | e.g. 84 | 88 | ``` 89 | 90 | ### NPM scripts 91 | 92 | - `npm t`: Run test suite 93 | - `npm start`: Run `npm run build` in watch mode 94 | - `npm run test:watch`: Run test suite in [interactive watch mode](http://facebook.github.io/jest/docs/cli.html#watch) 95 | - `npm run test:prod`: Run linting and generate coverage 96 | - `npm run build`: Generate bundles and typings, create docs 97 | - `npm run lint`: Lints code 98 | - `npm run commit`: Commit using conventional commit style ([husky](https://github.com/typicode/husky) will tell you to use it if you haven't :wink:) 99 | -------------------------------------------------------------------------------- /code-of-conduct.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at alexjovermorales@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /examples/basic/App.vue: -------------------------------------------------------------------------------- 1 | 7 | 8 | 41 | 42 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/.eslintignore: -------------------------------------------------------------------------------- 1 | /Users/igorhalfeld/Documents/projects/ouvue/dist 2 | /Users/igorhalfeld/Documents/projects/ouvue/dist/ouvue.es5.js 3 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | browser: true, 4 | es6: true 5 | }, 6 | extends: [ 7 | 'plugin:vue/essential', 8 | 'standard' 9 | ], 10 | globals: { 11 | Atomics: 'readonly', 12 | SharedArrayBuffer: 'readonly' 13 | }, 14 | parserOptions: { 15 | ecmaVersion: 2018, 16 | sourceType: 'module' 17 | }, 18 | plugins: [ 19 | 'vue' 20 | ], 21 | rules: { 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | /dist 4 | 5 | # local env files 6 | .env.local 7 | .env.*.local 8 | 9 | # Log files 10 | npm-debug.log* 11 | yarn-debug.log* 12 | yarn-error.log* 13 | pnpm-debug.log* 14 | 15 | # Editor directories and files 16 | .idea 17 | .vscode 18 | *.suo 19 | *.ntvs* 20 | *.njsproj 21 | *.sln 22 | *.sw? 23 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/README.md: -------------------------------------------------------------------------------- 1 | # with-ouvue-render-component 2 | 3 | ## Project setup 4 | ``` 5 | npm install 6 | ``` 7 | 8 | ### Compiles and hot-reloads for development 9 | ``` 10 | npm run serve 11 | ``` 12 | 13 | ### Compiles and minifies for production 14 | ``` 15 | npm run build 16 | ``` 17 | 18 | ### Lints and fixes files 19 | ``` 20 | npm run lint 21 | ``` 22 | 23 | ### Customize configuration 24 | See [Configuration Reference](https://cli.vuejs.org/config/). 25 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | '@vue/cli-plugin-babel/preset' 4 | ] 5 | } 6 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "with-ouvue-render-component", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "serve": "vue-cli-service serve", 7 | "build": "vue-cli-service build", 8 | "lint": "vue-cli-service lint" 9 | }, 10 | "dependencies": { 11 | "core-js": "^3.6.5", 12 | "vue": "^2.6.11" 13 | }, 14 | "devDependencies": { 15 | "@vue/cli-plugin-babel": "~4.4.0", 16 | "@vue/cli-plugin-eslint": "~4.4.0", 17 | "@vue/cli-service": "~4.4.0", 18 | "babel-eslint": "^10.1.0", 19 | "eslint": "^7.6.0", 20 | "eslint-config-standard": "^14.1.1", 21 | "eslint-plugin-import": "^2.22.0", 22 | "eslint-plugin-node": "^11.1.0", 23 | "eslint-plugin-promise": "^4.2.1", 24 | "eslint-plugin-standard": "^4.0.1", 25 | "eslint-plugin-vue": "^6.2.2", 26 | "vue-template-compiler": "^2.6.11" 27 | }, 28 | "browserslist": [ 29 | "> 1%", 30 | "last 2 versions", 31 | "not dead" 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IgorHalfeld/ouvue/92e02ef74c9fdce175987e8aee209eaeacf4a65d/examples/with-ouvue-render-component/public/favicon.ico -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | <%= htmlWebpackPlugin.options.title %> 9 | 10 | 11 | 14 |
15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/src/App.vue: -------------------------------------------------------------------------------- 1 | 12 | 13 | 18 | 19 | 29 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/src/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/IgorHalfeld/ouvue/92e02ef74c9fdce175987e8aee209eaeacf4a65d/examples/with-ouvue-render-component/src/assets/logo.png -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/src/components/HelloWorld.vue: -------------------------------------------------------------------------------- 1 | 32 | 33 | 41 | 42 | 43 | 59 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/src/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import services from './services' 3 | import App from './App.vue' 4 | 5 | import { create } from 'ouvue' 6 | // import { create } from '../../../dist/ouvue.es5' 7 | 8 | export const api = create({ services }) 9 | 10 | Object.defineProperty(Vue.prototype, '$services', { 11 | get: () => api, 12 | set () { 13 | throw new Error('Can\'t set $services') 14 | } 15 | }) 16 | 17 | Vue.config.productionTip = false 18 | 19 | const { OuvueRender } = api 20 | 21 | Vue.component('ouvue-render', OuvueRender) 22 | 23 | new Vue({ 24 | render: h => h(App) 25 | }).$mount('#app') 26 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/src/services/index.js: -------------------------------------------------------------------------------- 1 | import PostsService from './posts' 2 | 3 | const HTTPClient = window.fetch // think this like axios.create 4 | 5 | export default { 6 | posts: PostsService(HTTPClient) 7 | } 8 | -------------------------------------------------------------------------------- /examples/with-ouvue-render-component/src/services/posts.js: -------------------------------------------------------------------------------- 1 | export default HTTPClient => ({ 2 | async getAll () { 3 | console.log('Getting posts...') 4 | const res = await HTTPClient('https://jsonplaceholder.typicode.com/posts') 5 | const result = await res.json() 6 | 7 | return result 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /examples/with-prototype-and-service-structure/App.vue: -------------------------------------------------------------------------------- 1 | 7 | 8 | 25 | 26 | -------------------------------------------------------------------------------- /examples/with-prototype-and-service-structure/main.js: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import services from './services' 3 | import App from './App.vue' 4 | 5 | import { create } from '../../dist/ouvue.es5.js' 6 | 7 | const api = create({ services }) 8 | 9 | Object.defineProperty(Vue.prototype, '$services', { 10 | get: () => api, 11 | set() { 12 | throw new Error('Can\'t set $services') 13 | } 14 | }) 15 | 16 | new Vue({ 17 | el: '#app', 18 | render: h => h(App) 19 | }) 20 | -------------------------------------------------------------------------------- /examples/with-prototype-and-service-structure/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "with-prototype-and-service-structure", 3 | "version": "1.0.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "vue": { 8 | "version": "2.6.11", 9 | "resolved": "https://registry.npmjs.org/vue/-/vue-2.6.11.tgz", 10 | "integrity": "sha512-VfPwgcGABbGAue9+sfrD4PuwFar7gPb1yl1UK1MwXoQPAw0BKSqWfoYCT/ThFrdEVWoI51dBuyCoiNU9bZDZxQ==" 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/with-prototype-and-service-structure/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "with-prototype-and-service-structure", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "main.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [], 10 | "author": "", 11 | "license": "ISC", 12 | "dependencies": { 13 | "vue": "^2.6.11" 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /examples/with-prototype-and-service-structure/services/index.js: -------------------------------------------------------------------------------- 1 | import PostsService from './posts' 2 | 3 | const HTTPClient = window.fetch // think this like axios.create 4 | 5 | export default { 6 | posts: PostsService(HTTPClient) 7 | } 8 | -------------------------------------------------------------------------------- /examples/with-prototype-and-service-structure/services/posts.js: -------------------------------------------------------------------------------- 1 | export default HTTPClient => ({ 2 | async getAll () { 3 | console.log('Getting posts...') 4 | const res = await HTTPClient('https://jsonplaceholder.typicode.com/posts') 5 | const result = await res.json() 6 | 7 | return result 8 | } 9 | }) 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@ouvue/core", 3 | "version": "0.0.0-beta.2", 4 | "description": "Simple and scalable service layer(with cache 🤩) for Vue REST clients", 5 | "keywords": [], 6 | "main": "dist/ouvue.umd.js", 7 | "module": "dist/ouvue.es5.js", 8 | "typings": "dist/types/ouvue.d.ts", 9 | "files": [ 10 | "dist" 11 | ], 12 | "author": "Igor Halfeld ", 13 | "repository": { 14 | "type": "git", 15 | "url": "" 16 | }, 17 | "license": "MIT", 18 | "engines": { 19 | "node": ">=6.0.0" 20 | }, 21 | "scripts": { 22 | "lint": "tslint --project tsconfig.json -t codeFrame 'src/**/*.ts' 'test/**/*.ts'", 23 | "prebuild": "rimraf dist", 24 | "build": "rollup -c rollup.config.ts", 25 | "start": "rollup -c rollup.config.ts -w", 26 | "test": "jest --coverage", 27 | "test:watch": "jest --coverage --watch", 28 | "test:prod": "npm run lint && npm run test -- --no-cache", 29 | "deploy-docs": "ts-node tools/gh-pages-publish", 30 | "report-coverage": "cat ./coverage/lcov.info | coveralls", 31 | "commit": "git-cz", 32 | "semantic-release": "semantic-release", 33 | "semantic-release-prepare": "ts-node tools/semantic-release-prepare", 34 | "precommit": "lint-staged" 35 | }, 36 | "lint-staged": { 37 | "{src,test}/**/*.ts": [ 38 | "prettier --write", 39 | "git add" 40 | ] 41 | }, 42 | "config": { 43 | "commitizen": { 44 | "path": "node_modules/cz-conventional-changelog" 45 | } 46 | }, 47 | "jest": { 48 | "transform": { 49 | ".(ts|tsx)": "ts-jest", 50 | ".*\\.(vue)$": "vue-jest" 51 | }, 52 | "testEnvironment": "jsdom", 53 | "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$", 54 | "moduleFileExtensions": [ 55 | "ts", 56 | "tsx", 57 | "js", 58 | "vue" 59 | ], 60 | "coveragePathIgnorePatterns": [ 61 | "/node_modules/", 62 | "/test/" 63 | ], 64 | "coverageThreshold": { 65 | "global": { 66 | "branches": 90, 67 | "functions": 95, 68 | "lines": 95, 69 | "statements": 95 70 | } 71 | }, 72 | "collectCoverageFrom": [ 73 | "src/*.{js,ts}", 74 | "src/components/*.{js,ts,vue}" 75 | ] 76 | }, 77 | "prettier": { 78 | "semi": false, 79 | "singleQuote": true 80 | }, 81 | "commitlint": { 82 | "extends": [ 83 | "@commitlint/config-conventional" 84 | ] 85 | }, 86 | "devDependencies": { 87 | "@commitlint/cli": "^11.0.0", 88 | "@commitlint/config-conventional": "^7.1.2", 89 | "@types/jest": "^23.3.2", 90 | "@types/node": "^10.11.0", 91 | "@vue/test-utils": "^1.0.3", 92 | "colors": "^1.3.2", 93 | "commitizen": "^4.2.2", 94 | "coveralls": "^3.0.2", 95 | "cross-env": "^5.2.0", 96 | "cz-conventional-changelog": "^2.1.0", 97 | "husky": "^1.0.1", 98 | "jest": "^26.6.1", 99 | "jest-config": "^26.6.1", 100 | "lint-staged": "^8.0.0", 101 | "lodash.camelcase": "^4.3.0", 102 | "prettier": "^1.14.3", 103 | "prompt": "^1.0.0", 104 | "replace-in-file": "^3.4.2", 105 | "rimraf": "^2.6.2", 106 | "rollup": "^0.67.0", 107 | "rollup-plugin-commonjs": "^9.1.8", 108 | "rollup-plugin-json": "^3.1.0", 109 | "rollup-plugin-node-resolve": "^3.4.0", 110 | "rollup-plugin-sourcemaps": "^0.4.2", 111 | "rollup-plugin-typescript2": "^0.29.0", 112 | "semantic-release": "^17.1.1", 113 | "shelljs": "^0.8.3", 114 | "travis-deploy-once": "^5.0.9", 115 | "ts-jest": "^26.4.3", 116 | "ts-node": "^7.0.1", 117 | "tslint": "^5.11.0", 118 | "tslint-config-prettier": "^1.15.0", 119 | "tslint-config-standard": "^8.0.1", 120 | "typedoc": "^0.19.2", 121 | "typescript": "^3.0.3", 122 | "vue": "^2.6.11", 123 | "vue-jest": "^3.0.6", 124 | "vue-template-compiler": "^2.6.11" 125 | }, 126 | "dependencies": {} 127 | } 128 | -------------------------------------------------------------------------------- /rollup.config.ts: -------------------------------------------------------------------------------- 1 | import resolve from 'rollup-plugin-node-resolve' 2 | import commonjs from 'rollup-plugin-commonjs' 3 | import sourceMaps from 'rollup-plugin-sourcemaps' 4 | import camelCase from 'lodash.camelcase' 5 | import typescript from 'rollup-plugin-typescript2' 6 | import json from 'rollup-plugin-json' 7 | 8 | const pkg = require('./package.json') 9 | 10 | const libraryName = 'ouvue' 11 | 12 | export default { 13 | input: `src/${libraryName}.ts`, 14 | output: [ 15 | { file: pkg.main, name: camelCase(libraryName), format: 'umd', sourcemap: true }, 16 | { file: pkg.module, format: 'es', sourcemap: true }, 17 | ], 18 | // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash') 19 | external: [], 20 | watch: { 21 | include: 'src/**', 22 | }, 23 | plugins: [ 24 | // Allow json resolution 25 | json(), 26 | // Compile TypeScript files 27 | typescript({ useTsconfigDeclarationDir: true }), 28 | // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs) 29 | commonjs(), 30 | // Allow node_modules resolution, so you can use 'external' to control 31 | // which external modules to include in the bundle 32 | // https://github.com/rollup/rollup-plugin-node-resolve#usage 33 | resolve(), 34 | 35 | // Resolve source maps to the original source 36 | sourceMaps(), 37 | ], 38 | } 39 | -------------------------------------------------------------------------------- /src/cache.ts: -------------------------------------------------------------------------------- 1 | import { Strategy, CacheInstance } from './types' 2 | 3 | function createInmemory(): CacheInstance { 4 | const data = new Map() 5 | 6 | function set(key: string, value: T): void { 7 | data.set(key, value) 8 | } 9 | 10 | function get(key: string): T { 11 | return data.get(key) 12 | } 13 | 14 | function has(key: string): boolean { 15 | return Boolean(data.get(key)) 16 | } 17 | 18 | return { set, get, has } 19 | } 20 | 21 | export function create(strategy: string): CacheInstance { 22 | // @TODO: think in a better way to handle strategies 23 | const strategies: Strategy = { 24 | inmemory: createInmemory 25 | } 26 | 27 | return strategies[strategy]() 28 | } 29 | -------------------------------------------------------------------------------- /src/components/OuvueRender.ts: -------------------------------------------------------------------------------- 1 | import Vue, { CreateElement, VNode, VueConstructor } from 'vue' 2 | import { OuvueInstance } from '../types' 3 | 4 | interface Data { 5 | data: any 6 | isLoading: boolean 7 | error: any 8 | } 9 | 10 | interface Methods { 11 | fetch(): void 12 | } 13 | 14 | interface Props { 15 | action: string 16 | payload: Record 17 | options: Record 18 | } 19 | 20 | export default function createOuvueRenderComponent(fn: OuvueInstance['fetch']): VueConstructor { 21 | return Vue.extend({ 22 | name: 'OuvueRender', 23 | props: { 24 | action: { type: String, required: true }, 25 | payload: { type: Object, default: () => ({}) }, 26 | options: { type: Object, default: () => ({}) } 27 | }, 28 | data: () => ({ 29 | data: null, 30 | isLoading: false, 31 | error: null 32 | }), 33 | created() { 34 | this.fetch() 35 | }, 36 | methods: { 37 | async fetch(): Promise { 38 | this.isLoading = true 39 | const { data, error } = await fn(this.action, this.payload, this.options) 40 | 41 | this.data = data 42 | this.error = error 43 | this.isLoading = false 44 | } 45 | }, 46 | render(createElement: CreateElement): VNode { 47 | const slot = this.$scopedSlots.default!({ 48 | data: this.data, 49 | isLoading: this.isLoading, 50 | error: this.error 51 | }) as any 52 | 53 | return createElement('div', slot) 54 | } 55 | }) 56 | } 57 | -------------------------------------------------------------------------------- /src/ouvue.ts: -------------------------------------------------------------------------------- 1 | import * as Cache from './cache' 2 | import createOuvueRenderComponent from './components/OuvueRender' 3 | import { 4 | Options, 5 | Response, 6 | CacheInstance, 7 | CacheOptions, 8 | OuvueInstance, 9 | Nullable, 10 | FetchOptions 11 | } from './types' 12 | 13 | export function create(options: Options): OuvueInstance { 14 | const services: { [key: string]: any } = options.services ?? {} 15 | const cacheOpts: CacheOptions = options.cache ?? { strategy: 'inmemory' } 16 | 17 | const cache: CacheInstance = Cache.create(cacheOpts.strategy) 18 | 19 | async function fetch(key: string): Promise>> 20 | async function fetch( 21 | key: string, 22 | payload?: Record 23 | ): Promise>> 24 | async function fetch( 25 | key: string, 26 | payload?: Record, 27 | options?: FetchOptions 28 | ): Promise>> { 29 | const [entity, action] = key.trim().split('/') 30 | let data: Nullable 31 | 32 | if (cache.has(key) && !options?.onlyNetwork) { 33 | data = cache.get(key) 34 | const response: Response> = { 35 | data, 36 | error: null 37 | } 38 | return response 39 | } 40 | 41 | if (!services[entity] || !services[entity][action]) { 42 | if (process.env.NODE_ENV !== 'production') { 43 | console.warn(`${key} not found on services object`) 44 | } 45 | 46 | const response: Response> = { 47 | data: null, 48 | error: { message: `${key} not found on services object` } 49 | } 50 | return response 51 | } 52 | 53 | try { 54 | data = await services[entity][action](payload) 55 | cache.set(key, data) 56 | } catch (err) { 57 | const response: Response> = { 58 | data: null, 59 | error: { 60 | ...err, 61 | message: 'some error happen on request call' 62 | } 63 | } 64 | 65 | return response 66 | } 67 | 68 | const result: Response> = { 69 | data, 70 | error: null 71 | } 72 | return result 73 | } 74 | 75 | return { fetch, OuvueRender: createOuvueRenderComponent(fetch) } 76 | } 77 | -------------------------------------------------------------------------------- /src/types/index.ts: -------------------------------------------------------------------------------- 1 | import { VueConstructor } from 'vue' 2 | 3 | export type CacheOptions = { 4 | strategy: string 5 | } 6 | 7 | export type Options = { 8 | cache?: CacheOptions 9 | services?: T 10 | } 11 | 12 | export interface CacheInstance { 13 | set(key: string, value: T): void 14 | get(key: string): T 15 | has(key: string): boolean 16 | } 17 | 18 | export interface OuvueInstance { 19 | fetch( 20 | key: string, 21 | payload?: Record, 22 | options?: any 23 | ): Promise>> 24 | OuvueRender: VueConstructor 25 | } 26 | 27 | export type Nullable = T | null 28 | 29 | export interface Strategy { 30 | [key: string]: any 31 | inmemory(): CacheInstance 32 | } 33 | 34 | export type Response = { 35 | data: T 36 | error: Nullable 37 | } 38 | 39 | export type FetchOptions = { 40 | onlyNetwork: boolean 41 | } 42 | -------------------------------------------------------------------------------- /test/OuvueRender.test.ts: -------------------------------------------------------------------------------- 1 | import Vue from 'vue' 2 | import { shallowMount } from '@vue/test-utils' 3 | import { create } from '../src/ouvue' 4 | import { OuvueInstance } from '../src/types' 5 | 6 | type User = { 7 | id?: number 8 | name?: string 9 | } 10 | 11 | interface UserService { 12 | getAll(): Promise 13 | throwAnError(): Error 14 | } 15 | 16 | interface Services { 17 | users: UserService 18 | } 19 | 20 | let user = { id: 444, name: 'Test' } 21 | let instance: OuvueInstance 22 | const services: Services = { 23 | users: { 24 | getAll: () => Promise.resolve([user]), 25 | throwAnError: () => { 26 | throw new Error('UserService - error on users service') 27 | } 28 | } 29 | } 30 | 31 | describe('OuvueRender', () => { 32 | beforeEach(() => { 33 | instance = create({ services }) 34 | }) 35 | 36 | it('should fetch data from entity/action', async () => { 37 | const wrapper = shallowMount }>(instance.OuvueRender, { 38 | propsData: { 39 | action: 'users/getAll' 40 | }, 41 | scopedSlots: { 42 | default: '
{{ data }}
' 43 | } 44 | }) 45 | 46 | await wrapper.vm.fetch() 47 | 48 | const text = JSON.parse(wrapper.text()) 49 | expect(text).toEqual([{ id: 444, name: 'Test' }]) 50 | }) 51 | 52 | it('should respect options received by props', async () => { 53 | const wrapper = shallowMount }>(instance.OuvueRender, { 54 | propsData: { 55 | action: 'users/getAll', 56 | options: { onlyNetwork: true } 57 | }, 58 | scopedSlots: { 59 | default: '
{{ data }}
' 60 | } 61 | }) 62 | 63 | await wrapper.vm.fetch() 64 | 65 | const text1 = JSON.parse(wrapper.text()) 66 | expect(text1).toEqual([{ id: 444, name: 'Test' }]) 67 | 68 | const u = { ...user, id: 555 } 69 | user = u 70 | 71 | await wrapper.vm.fetch() 72 | 73 | const text2 = JSON.parse(wrapper.text()) 74 | expect(text2).toEqual([{ id: 555, name: 'Test' }]) 75 | }) 76 | 77 | it('should return a error from entity/action', async () => { 78 | const wrapper = shallowMount }>(instance.OuvueRender, { 79 | propsData: { 80 | action: 'users/throwAnError' 81 | }, 82 | scopedSlots: { 83 | default: '
{{ error }}
' 84 | } 85 | }) 86 | 87 | await wrapper.vm.fetch() 88 | 89 | const text = JSON.parse(wrapper.text()) 90 | expect(text).toEqual({ 91 | message: 'some error happen on request call' 92 | }) 93 | }) 94 | }) 95 | -------------------------------------------------------------------------------- /test/cache.test.ts: -------------------------------------------------------------------------------- 1 | import * as Cache from '../src/cache' 2 | import { CacheInstance } from '../src/types' 3 | 4 | let data: CacheInstance 5 | 6 | type TestPayload = { 7 | name: string 8 | } 9 | 10 | describe('Cache', () => { 11 | beforeEach(() => { 12 | data = Cache.create('inmemory') 13 | data.set('test', { name: 'testing' }) 14 | }) 15 | 16 | it('should return true when pass a existing key', () => { 17 | expect(data.has('test')).toBe(true) 18 | }) 19 | 20 | it('should return false when pass a not found key', () => { 21 | expect(data.has('testblabla')).toBe(false) 22 | }) 23 | 24 | it('should return correct payload to a valid key', () => { 25 | expect(data.get('test')).toEqual({ name: 'testing' }) 26 | }) 27 | 28 | it('should set a value to a key', () => { 29 | data.set('test2', { name: 'testing2' }) 30 | expect(data.get('test2')).toEqual({ name: 'testing2' }) 31 | }) 32 | }) 33 | -------------------------------------------------------------------------------- /test/ouvue.test.ts: -------------------------------------------------------------------------------- 1 | import { create } from '../src/ouvue' 2 | import { OuvueInstance } from '../src/types' 3 | 4 | type User = { 5 | id?: number 6 | name?: string 7 | } 8 | 9 | interface UserService { 10 | getById({ id }: { id: number }): User 11 | getAll(): User[] 12 | update({ name }: { name: string }): void 13 | throwAnError(): void 14 | } 15 | 16 | interface Services { 17 | users: UserService 18 | } 19 | 20 | let user: User = { id: 444, name: 'Test' } 21 | 22 | let instance: OuvueInstance 23 | const services: Services = { 24 | users: { 25 | getAll: () => [user], 26 | getById: ({ id }: { id: number }): User => { 27 | return [user].find(u => u.id === id) ?? {} 28 | }, 29 | update: ({ name }) => { 30 | // to test, needs to create another object to change the ref 31 | const u = { ...user, name } 32 | user = u 33 | }, 34 | throwAnError() { 35 | throw new Error('throw an error') 36 | } 37 | } 38 | } 39 | 40 | describe('Ouvue', () => { 41 | beforeEach(() => { 42 | instance = create({ services }) 43 | }) 44 | 45 | it('should create a valid instance', () => { 46 | expect(instance.fetch).toBeTruthy() 47 | }) 48 | 49 | it('should not break when not pass services', async () => { 50 | const i = create({}) 51 | const response = await i.fetch('users/getAll', { name: 'Test getAll' }) 52 | 53 | expect(response).toEqual({ 54 | data: null, 55 | error: { message: 'users/getAll not found on services object' } 56 | }) 57 | }) 58 | it('should not break when not pass services', async () => { 59 | const i = create({ cache: { strategy: 'inmemory' } }) 60 | const response = await i.fetch('users/getAll', { name: 'Test getAll' }) 61 | 62 | expect(response).toEqual({ 63 | data: null, 64 | error: { message: 'users/getAll not found on services object' } 65 | }) 66 | }) 67 | 68 | it('should not break when pass a unknown key', async () => { 69 | const response = await instance.fetch('users/create', { name: 'Test create' }) 70 | 71 | expect(response).toEqual({ 72 | data: null, 73 | error: { message: 'users/create not found on services object' } 74 | }) 75 | }) 76 | 77 | it('should not broke when pass a unknown key and now show a warning when production', async () => { 78 | process.env.NODE_ENV = 'production' 79 | const response = await instance.fetch('users/create', { name: 'Test create' }) 80 | 81 | expect(response).toEqual({ 82 | data: null, 83 | error: { message: 'users/create not found on services object' } 84 | }) 85 | }) 86 | 87 | it('should fetch correct payload calling a right service', async () => { 88 | const response = await instance.fetch('users/getById', { id: 444 }) 89 | expect(response.data).toEqual({ name: 'Test', id: 444 }) 90 | expect(response.error).toBeNull() 91 | }) 92 | 93 | it('should work without a payload for getAll methods', async () => { 94 | const response = await instance.fetch('users/getAll') 95 | expect(response.data).toEqual([{ name: 'Test', id: 444 }]) 96 | expect(response.error).toBeNull() 97 | }) 98 | 99 | it('should fetch correct payload calling a right service', async () => { 100 | const response = await instance.fetch('users/getById', { id: 444 }) 101 | expect(response.data).toEqual({ name: 'Test', id: 444 }) 102 | expect(response.error).toBeNull() 103 | 104 | const updateRes = await instance.fetch('users/update', { name: 'Test 2' }) 105 | expect(updateRes.error).toBeNull() 106 | 107 | const response2 = await instance.fetch('users/getById', { id: 444 }) 108 | expect(response2.data).toEqual({ name: 'Test', id: 444 }) 109 | expect(response2.error).toBeNull() 110 | 111 | // Use `onlyNetwork` to not check cache 112 | const response3 = await instance.fetch( 113 | 'users/getById', 114 | { id: 444 }, 115 | { onlyNetwork: true } 116 | ) 117 | expect(response3.data).toEqual({ name: 'Test 2', id: 444 }) 118 | expect(response3.error).toBeNull() 119 | 120 | // After use onlyNetwork, the cache was updated 121 | const response4 = await instance.fetch('users/getById', { id: 444 }) 122 | expect(response4.data).toEqual({ name: 'Test 2', id: 444 }) 123 | expect(response4.error).toBeNull() 124 | }) 125 | 126 | it('should throw an error if service fail', async () => { 127 | const response = await instance.fetch('users/throwAnError') 128 | expect(response.data).toBeNull() 129 | expect(response.error).toEqual({ message: 'some error happen on request call' }) 130 | }) 131 | }) 132 | -------------------------------------------------------------------------------- /tools/gh-pages-publish.ts: -------------------------------------------------------------------------------- 1 | const { cd, exec, echo, touch } = require("shelljs") 2 | const { readFileSync } = require("fs") 3 | const url = require("url") 4 | 5 | let repoUrl 6 | let pkg = JSON.parse(readFileSync("package.json") as any) 7 | if (typeof pkg.repository === "object") { 8 | if (!pkg.repository.hasOwnProperty("url")) { 9 | throw new Error("URL does not exist in repository section") 10 | } 11 | repoUrl = pkg.repository.url 12 | } else { 13 | repoUrl = pkg.repository 14 | } 15 | 16 | let parsedUrl = url.parse(repoUrl) 17 | let repository = (parsedUrl.host || "") + (parsedUrl.path || "") 18 | let ghToken = process.env.GH_TOKEN 19 | 20 | echo("Deploying docs!!!") 21 | cd("docs") 22 | touch(".nojekyll") 23 | exec("git init") 24 | exec("git add .") 25 | exec('git config user.name "Igor Halfeld"') 26 | exec('git config user.email "hello@igorluiz.me"') 27 | exec('git commit -m "docs(docs): update gh-pages"') 28 | exec( 29 | `git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages` 30 | ) 31 | echo("Docs deployed!!") 32 | -------------------------------------------------------------------------------- /tools/semantic-release-prepare.ts: -------------------------------------------------------------------------------- 1 | const path = require("path") 2 | const { fork } = require("child_process") 3 | const colors = require("colors") 4 | 5 | const { readFileSync, writeFileSync } = require("fs") 6 | const pkg = JSON.parse( 7 | readFileSync(path.resolve(__dirname, "..", "package.json")) 8 | ) 9 | 10 | pkg.scripts.prepush = "npm run test:prod && npm run build" 11 | pkg.scripts.commitmsg = "commitlint -E HUSKY_GIT_PARAMS" 12 | 13 | writeFileSync( 14 | path.resolve(__dirname, "..", "package.json"), 15 | JSON.stringify(pkg, null, 2) 16 | ) 17 | 18 | // Call husky to set up the hooks 19 | fork(path.resolve(__dirname, "..", "node_modules", "husky", "lib", "installer", 'bin'), ['install']) 20 | 21 | console.log() 22 | console.log(colors.green("Done!!")) 23 | console.log() 24 | 25 | if (pkg.repository.url.trim()) { 26 | console.log(colors.cyan("Now run:")) 27 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 28 | console.log(colors.cyan(" semantic-release-cli setup")) 29 | console.log() 30 | console.log( 31 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 32 | ) 33 | console.log() 34 | console.log( 35 | colors.gray( 36 | 'Note: Make sure "repository.url" in your package.json is correct before' 37 | ) 38 | ) 39 | } else { 40 | console.log( 41 | colors.red( 42 | 'First you need to set the "repository.url" property in package.json' 43 | ) 44 | ) 45 | console.log(colors.cyan("Then run:")) 46 | console.log(colors.cyan(" npm install -g semantic-release-cli")) 47 | console.log(colors.cyan(" semantic-release-cli setup")) 48 | console.log() 49 | console.log( 50 | colors.cyan('Important! Answer NO to "Generate travis.yml" question') 51 | ) 52 | } 53 | 54 | console.log() 55 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "moduleResolution": "node", 4 | "target": "es5", 5 | "module": "es2015", 6 | "lib": ["es2015", "es2016", "es2017", "dom"], 7 | "strict": true, 8 | "esModuleInterop": true, 9 | "sourceMap": true, 10 | "declaration": true, 11 | "allowSyntheticDefaultImports": true, 12 | "experimentalDecorators": true, 13 | "emitDecoratorMetadata": true, 14 | "declarationDir": "dist/types", 15 | "outDir": "dist/lib", 16 | "typeRoots": ["node_modules/@types", "vue", "@vue/test-utils"] 17 | }, 18 | "include": ["src"] 19 | } 20 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "tslint-config-standard", 4 | "tslint-config-prettier" 5 | ] 6 | } --------------------------------------------------------------------------------