💎 Elegant and simple way to build requests for REST API

Overview

Elegant and simple way to build requests for REST API

This package helps you quickly to build requests for REST API. Move your logic and backend requests to dedicated classes. Keep your code clean and elegant.

🔥 If you use Laravel, this package matches perfectly with spatie/laravel-query-builder.

Links

Contributors

Thanks to the following people who have contributed to this project:

See all contributors

Thanks

Why another package if we have those? Because currently (march, 2018) they restricted backend response to JSON API specification.

Contact

Twitter @robsontenorio

Comments
  • Implement Model.withoutWrapping to return full response when set to false

    Implement Model.withoutWrapping to return full response when set to false

    Fixes #54

    You can disable response unwrapping by setting one simple var:

    Model.withoutWrapping = false
    

    Tests included, please let me know if you can merge it 👍

    Edit: Kind of a big change to support nested unwrapping of data. Example API response, Model.withoutWrapping to false returns the same result:

    {
      data: [
        {
          id: 1,
          someId: 'ap319-0nh56',
          firstname: 'John',
          lastname: 'Doe',
          age: 25,
          comments: {
            data: [
              {
                id: 1,
                post_id: 1,
                someId: 'ma018-9ha12',
                text: 'Hello'
              },
              {
                id: 2,
                post_id: 1,
                someId: 'mw012-7ha19',
                text: 'How are you?'
              }
            ]
          }
        },
        {
          id: 1,
          someId: 'by887-0nv66',
          firstname: 'Mary',
          lastname: 'Doe',
          age: 25,
          comments: {
            data: [
              {
                id: 1,
                post_id: 1,
                someId: 'ma018-9ha12',
                text: 'Hello'
              },
              {
                id: 2,
                post_id: 1,
                someId: 'mw012-7ha19',
                text: 'How are you?'
              }
            ]
          }
        }
      ]
    }
    

    When Model.withoutWrapping is set to true (or not defined) we return it like this:

    [
        {
          id: 1,
          someId: 'ap319-0nh56',
          firstname: 'John',
          lastname: 'Doe',
          age: 25,
          comments: [
              {
                id: 1,
                post_id: 1,
                someId: 'ma018-9ha12',
                text: 'Hello'
              },
              {
                id: 2,
                post_id: 1,
                someId: 'mw012-7ha19',
                text: 'How are you?'
              }
          ]
        },
        {
          id: 1,
          someId: 'by887-0nv66',
          firstname: 'Mary',
          lastname: 'Doe',
          age: 25,
          comments: [
              {
                id: 1,
                post_id: 1,
                someId: 'ma018-9ha12',
                text: 'Hello'
              },
              {
                id: 2,
                post_id: 1,
                someId: 'mw012-7ha19',
                text: 'How are you?'
              }
          ]
        }
    ]
    opened by peterquentin 14
  • Upload a PDF file

    Upload a PDF file

    Hello there,

    I am trying to use this awesome plugin to upload a PDF file. I have created a model for this:

    import Model from './Model';
    
    export default class JobApplication extends Model {
      resource() {
        return 'v2/job_applications';
      }
    }
    

    Then, I call the model within the .vue file like that:

    ...
     import JobApplication from "./../models/JobApplication";
    ...
    async onSubmit() {
      let job = new JobApplication({
        first_name,
        last_name,
        email,
        mobile_phone,
        resume: this.$refs.resume.files[0]
      });
      await job
        .save()
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.error(error.response);
        });
    }
    ...
    

    The problem is that the POST request fails every time I try to submit the form because of the resume field. What am I doing wrong in here? Do I have to do any extra steps? Thank you

    enhancement released 
    opened by Tes3awy 13
  • feat(builder): add support to nested filters

    feat(builder): add support to nested filters

    Add support to nested filters to where and whereIn.

    Closes #81

    TODO

    • [x] Update documentation of where and whereIn

    Usage

    await Model.where(['user', 'status'], 'active').get()
    // GET /resource?filter[user][status]=active
    
    await Model.whereIn(['user', 'status'], ['active', 'inactive']).get()
    // GET /resource?filter[user][status]=active,inactive
    
    released 
    opened by JoaoPedroAS51 11
  • data wrapping, model hydratation and access to response instance

    data wrapping, model hydratation and access to response instance

    This pull request is to handle request to JSON API’s with and without data wrapping. Basically you only need to configure your model and define how your data is wrapper in each response operation.

    Configration

    You only need to define de value of dataWrappers()
    By default, all models operate without data wrapping, for backward compatibility.

      dataWrappers() {
        return {
          index: null,
          store: null,
          show: null,
          update: null,
          destroy: null,
        }
      }
    

    So, if your API returns all your data inside a data attribute, then you should set up dataWrappers() like this:

      dataWrappers() {
        return {
          index: 'data',
          store: 'data',
          show: 'data',
          update: 'data',
          destroy: 'data',
        }
      }
    

    In case your API only wraps the resources collections, then, you only need to set up that response type:

     dataWrappers() {
       return {
         index: 'data',
         store: null,
         show: null,
         update: null,
         destroy: null,
       }
     }
    

    Well, you get the idea...

    Model Instance hydration

    Another thing this pull request solves is the model hydratation. All models will be hydratated after each CRUD operation. This is usefull if your API returns a full representation of the resource. This avoids a second request to get the new values.

     // resource before request
     // {
     //   id: 1,
     //   username: 'arya'
     //   email: '[email protected]'
     //   token: '1234'
     // }
    
     // PUT /users/1
     let user = new User({ id: 1, email: '[email protected]' })
     await user.save()
    
     // response from API for PUT /users/1
     // {
     //   data: {
     //     id: 1,
     //     username: 'arya'
     //     email: '[email protected]'
     //     token: '1234'
     //   }
     // }
    
     user = {
       id: 1,
       username: 'arya'
       email: '[email protected]'
       token: '1234'
     }
    

    This is very useful even for a DELETE request, if you return the deleted values.

    Access to response instance on save.

    Finally, now, method save() returns the response instance unmodified. The models are stored in the instance itself (hydrated), but the returned value is the http response. Again, this is useful if we want to access metadata information in the response data.

      let user = new User({name: 'Arya'})
      res = user.save()
    
      // "user" is the User Instance
      user = {
        id: 1,
        name: 'arya',
      }
    
      // "res" is the http response
      res = {  
        data: {},
        status: 200,
        statusText: 'OK',
        headers: {},
        config: {},
        request: {}  
      }
    

    Tests...

    I've added test for all the cases (I think). By the way, I added some "deprecated" comments (in tests) for methods $get(), $first(), $find() as I think those methods are redundant now? I don't know, what do you think?

    opened by jaumesala 10
  • Documentation navigation: URLs for

    Documentation navigation: URLs for "On this page" go to the starting page instead of the respective section

    To reproduce: Visit for example Relationship Operations.

    Expected behaviour: Opening links for "On this page" in a new window (on the right in widescreen layout) should link to their respective sections in the documentation.
    Linking to specific headlines in the documentation is especially useful so we can send people to a specific section of a documentation page.

    What actually happens: The navigation only works when left clicking. Opening the resulting URL in a new browser window leads back to the documentation's starting page. The underlying links are not working correctly.
    Additionally, hovering over a headline and clicking the # also links back to the documentation's starting page.

    released documentation 
    opened by Peter-Krebs 9
  • Catching Errors on model.save()

    Catching Errors on model.save()

    Hello,

    I am trying to catch error on POST data.

    My code:

    <form
              @submit.prevent="onSubmit"
              class="apply-form-section__form"
              action
              method="POST"
              ref="form"
              role="form"
            >
              <div class="apply-form-section__input-wrapper">
                <input
                  type="text"
                  class="apply-form-section__input-wrapper--input-field"
                  placeholder="Name"
                  v-model.lazy.trim="formResponses.name"
                >
              </div>
              <div class="apply-form-section__input-wrapper">
                <input
                  type="tel"
                  class="apply-form-section__input-wrapper--input-field"
                  placeholder="Phone number"
                  v-model.lazy.trim="formResponses.mobile"
                >
              </div>
              <div class="apply-form-section__input-wrapper">
                <input
                  type="text"
                  class="apply-form-section__input-wrapper--input-field"
                  placeholder="Company"
                  v-model.lazy.trim="formResponses.company"
                >
              </div>
    </form>
    
    data() {
          return {
            formResponses: {
              name: "",
              mobile: "",
              company: "",
              position: "",
              email: ""
            },
          };
        },
    methods: {
          async onSubmit() {
            console.log("form responses:", this.formResponses);
            let newApplication = new CardApplication({
              name: this.formResponses.name,
              mobile_phone: this.formResponses.mobile,
              company: this.formResponses.company,
              position: this.formResponses.position,
              email: this.formResponses.email
            });
    
            await newApplication
              .save()
              .then(response => {
                this.formSubmitted = true;
                if(response.meta.code == 200) {
                  console.log("success:", response);
                  console.log("form data:", this.formResponses);
                }
              })
              .catch(err => {
                console.log("ERROR SAVING APPLICATION:", err);
              });
          }
    

    The problem is that I don't get the supposed response object on error. I only get Error: Request failed with status code 400 in the console.

    Can you help me with this?

    opened by Tes3awy 9
  • updating the object sends a POST request

    updating the object sends a POST request

    Here is the code I have that I am using to update and I can get the save/update to work?

    this.productObj = await Product.include('variants', 'additional_info', 'nutrition_fact')
                    .append('min_priced_variant')
                    .find(this.productId)
    
    this.productObj.name = 'Test';
    this.productObj.category_id = 3;
    
    this.productObj.save();
    

    Is there any reason why this would send a POST request to /products instead of a PUT request to /products/{id}.

    Am I missing something?

    opened by abishekrsrikaanth 9
  • Possible dependencies/devDependencies defined wrong

    Possible dependencies/devDependencies defined wrong

    Today I updated to package version 1.4.1. Now, when I compile my code, I get:

    These dependencies were not found:
    
    * @babel/runtime/helpers/assertThisInitialized in ./node_modules/vue-api-query/build/Model.js
    * @babel/runtime/helpers/classCallCheck in ./node_modules/vue-api-query/build/StaticModel.js, ./node_modules/vue-api-query/build/Parser.js and 2 others
    * @babel/runtime/helpers/createClass in ./node_modules/vue-api-query/build/Model.js, ./node_modules/vue-api-query/build/StaticModel.js and 2 others
    * @babel/runtime/helpers/getPrototypeOf in ./node_modules/vue-api-query/build/Model.js
    * @babel/runtime/helpers/inherits in ./node_modules/vue-api-query/build/Model.js
    * @babel/runtime/helpers/interopRequireDefault in ./node_modules/vue-api-query/build/index.js, ./node_modules/vue-api-query/build/StaticModel.js and 3 others
    * @babel/runtime/helpers/possibleConstructorReturn in ./node_modules/vue-api-query/build/Model.js
    * @babel/runtime/helpers/slicedToArray in ./node_modules/vue-api-query/build/Builder.js
    
    To install them, you can run: npm install --save @babel/runtime/helpers/assertThisInitialized @babel/runtime/helpers/classCallCheck @babel/runtime/helpers/createClass @babel/runtime/helpers/getPrototypeOf @babel/runtime/helpers/inherits @babel/runtime/helpers/interopRequireDefault @babel/runtime/helpers/possibleConstructorReturn @babel/runtime/helpers/slicedToArray 
    

    I think, there are some dependencies are needed in the "dependencies" section, not "devDependencies". So far I can reconstruct, the error starts with 1.3.0

    opened by prodigy7 9
  • data wrapping for single items

    data wrapping for single items

    It is typical for JSON API's to wrap not only multiple results but also single results in a data key. (Even Laravel's API Resources default to this behaviour.)

    For multiple results (arrays of items), vue-api-query automagically works regardless of whether or not the data key wrapper is present.

    I feel that for single results there should be the same behaviour.

    Backward-compatibility can be ensured by adding a configuration option or optional function argument to enable this behaviour. (Similar to withoutWrapping in Laravel's API Resources. See Eloquent: API Resources)

    So, if the backend responds with:

    {
        "data": {
            id: 1,
            firstname: "John",
            lastname: "Doe",
            age: 25
        }
    }
    

    And withWrapping is set to true, the behaviour should be the same as if the response was:

    {
        id: 1,
        firstname: "John",
        lastname: "Doe",
        age: 25
    }
    
    opened by derekphilipau 9
  • Q: How do I add properties to `this` on models correctly?

    Q: How do I add properties to `this` on models correctly?

    I had trouble defining custom properties on the models, maybe you have a best-practice approach for me on this, as my current fix is a workaround.

    I went and added a custom property to my base class for vue-js-api models (I have a getter and setter as well):

    MyModelBase.js

      constructor(...args) {
        super(args);
        
        this._myProp = "";
        
        return this;
      }
    

    Initializing a Model with the constructor resulted in exceptions in the browser console.

    page.vue

      // This throws an error in the console, that `.include()` is not a function
      await MyModel
        .include(['test'])
        .first()
        .then( response => () {} )
        
        ...
    

    I realised later that adding the constructor did something bad.
    Consider your Model's constructor:

    Model.js

      constructor(...atributtes) {
        super()
    
        if (atributtes.length === 0) {
          this._builder = new Builder(this)
        } else {
          Object.assign(this, ...atributtes)
        }
        
        ...
      }
    

    The else portion there skips initializing this._builder - probably because you assume it is of on of your Models and already has a _builder. But in this case it's called from my custom constructor.

    I fixed adding _builder in the constructor of my base class, which is of course not future-proof. It currently works for my use-cases.

        // Added after the call to super()
        this._builder = new Builder(this);
    

    Q: Am I adding the custom constructor incorrectly? Is there an alternative way to add properties to this?

    PS: The correct spelling is attributes, not atributtes.
    Is this intentional? Or is this an ES6 thing where attributes is a reserved word?
    Maybe you are handling an unknown number of butts with atritis?
    In that case it should be atriButts :)

    Edit: Formatting

    opened by Peter-Krebs 9
  • Importing doesn't work

    Importing doesn't work

    Failed to compile with 2 errors
    This dependency was not found:
    
    * vue-api-query in ./src/boot/axios.js, ./src/models/Model.js
    
    To install it, you can run: npm install --save vue-api-query
    
    import { Model } from 'vue-api-query'
    import axios from 'axios'
    
    [...]
    

    Downgrading to 1.5.2 solves the issue.

    opened by francoism90 8
  • Exporting data as Excel

    Exporting data as Excel

    Hi,

    i would use the same query builder syntax to export data as Excel.

    For example, calling:

    User.
        .where(toRaw(filters.value))
        .orderBy((descending ? '-' : '') + sortBy)
        .export('users.xlsx');
    

    would call /users/export with the same querystring parameters of get() method and then use a snippet similar to

    axios.get(url, { responseType: 'blob' })
          .then(response => {
            const blob = new Blob([response.data], { type: 'application/pdf' })
            const link = document.createElement('a')
            link.href = URL.createObjectURL(blob)
            link.download = label
            link.click()
            URL.revokeObjectURL(link.href)
    

    or https://www.npmjs.com/package/file-saver

    I'm using https://docs.laravel-excel.com/3.1/exports/ and would be incredibly helpful replicate the same get() behaviour exporting the Excel from

    public function export()
        {
            $data = QueryBuilder::for(User::class)
                ->allowedFilters(['soggetto', 'soggetto.nominativo', 'login', 'tipo_utente', 'roles.id'])
                ->allowedIncludes(['soggetto'])
                ->with('soggetto')
                ->get();
    
            return Excel::download(new UsersExport($data), 'users.xlsx');
        }
    

    Maybe is already possible with some hack :)

    Thanks

    opened by fbramato 0
  • chore: bump express from 4.17.1 to 4.18.2 in /docs

    chore: bump express from 4.17.1 to 4.18.2 in /docs

    Bumps express from 4.17.1 to 4.18.2.

    Release notes

    Sourced from express's releases.

    4.18.2

    4.18.1

    • Fix hanging on large stack of sync routes

    4.18.0

    ... (truncated)

    Changelog

    Sourced from express's changelog.

    4.18.2 / 2022-10-08

    4.18.1 / 2022-04-29

    • Fix hanging on large stack of sync routes

    4.18.0 / 2022-04-25

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • chore: bump decode-uri-component from 0.2.0 to 0.2.2 in /docs

    chore: bump decode-uri-component from 0.2.0 to 0.2.2 in /docs

    Bumps decode-uri-component from 0.2.0 to 0.2.2.

    Release notes

    Sourced from decode-uri-component's releases.

    v0.2.2

    • Prevent overwriting previously decoded tokens 980e0bf

    https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.1...v0.2.2

    v0.2.1

    • Switch to GitHub workflows 76abc93
    • Fix issue where decode throws - fixes #6 746ca5d
    • Update license (#1) 486d7e2
    • Tidelift tasks a650457
    • Meta tweaks 66e1c28

    https://github.com/SamVerschueren/decode-uri-component/compare/v0.2.0...v0.2.1

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
  • chore: bump qs from 6.9.4 to 6.9.7

    chore: bump qs from 6.9.4 to 6.9.7

    Bumps qs from 6.9.4 to 6.9.7.

    Changelog

    Sourced from qs's changelog.

    6.9.7

    • [Fix] parse: ignore __proto__ keys (#428)
    • [Fix] stringify: avoid encoding arrayformat comma when encodeValuesOnly = true (#424)
    • [Robustness] stringify: avoid relying on a global undefined (#427)
    • [readme] remove travis badge; add github actions/codecov badges; update URLs
    • [Docs] add note and links for coercing primitive values (#408)
    • [Tests] clean up stringify tests slightly
    • [meta] fix README.md (#399)
    • Revert "[meta] ignore eclint transitive audit warning"
    • [actions] backport actions from main
    • [Dev Deps] backport updates from main

    6.9.6

    • [Fix] restore dist dir; mistakenly removed in d4f6c32

    6.9.5

    • [Fix] stringify: do not encode parens for RFC1738
    • [Fix] stringify: fix arrayFormat comma with empty array/objects (#350)
    • [Refactor] format: remove util.assign call
    • [meta] add "Allow Edits" workflow; update rebase workflow
    • [actions] switch Automatic Rebase workflow to pull_request_target event
    • [Tests] stringify: add tests for #378
    • [Tests] migrate tests to Github Actions
    • [Tests] run nyc on all tests; use tape runner
    • [Dev Deps] update eslint, @ljharb/eslint-config, browserify, mkdirp, object-inspect, tape; add aud
    Commits
    • 4cd0032 v6.9.7
    • e799ba5 [Fix] parse: ignore __proto__ keys (#428)
    • 02ca358 [Robustness] stringify: avoid relying on a global undefined (#427)
    • 4a17709 [Fix] stringify: avoid encoding arrayformat comma when `encodeValuesOnly = ...
    • c0e13e9 [readme] remove travis badge; add github actions/codecov badges; update URLs
    • 4113a5f [Tests] clean up stringify tests slightly
    • 749a584 [Docs] add note and links for coercing primitive values (#408)
    • cce2082 [meta] fix README.md (#399)
    • c44f0c5 Revert "[meta] ignore eclint transitive audit warning"
    • e6cfd8b [actions] backport actions from main
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Releases(v1.11.0)
  • v1.11.0(Nov 21, 2022)

  • v1.10.0(Jul 5, 2022)

  • v1.9.1(May 25, 2021)

  • v1.9.0(Jan 17, 2021)

  • v1.8.2(Dec 4, 2020)

  • v1.8.1(Nov 10, 2020)

  • v1.8.0(Nov 10, 2020)

  • v1.7.1(Nov 1, 2020)

  • v1.7.0(Oct 31, 2020)

    Features

    • model: handle 'data' wrapped responses for create and update (#109) (1bc6248) (@fadugyamfi)
    • model: add support to nested keys for relations (#127) (095c1c3) (@JoaoPedroAS51)

    Bug Fixes

    • model: add null check in isValidId (#115) (279f9dc) (@guirociozanini)
    • model: relations are not being applied if any is null (#134) (92932cc) (@JoaoPedroAS51)

    Docs

    • add new documentation website :tada: (#130) (e1afa2a) (@JoaoPedroAS51)

    See https://robsontenorio.github.io/vue-api-query/

    Source code(tar.gz)
    Source code(zip)
  • 1.6.1(Oct 9, 2020)

  • 1.6.0(Oct 9, 2020)

    Thanks @JoaoPedroAS51 !

    You can also apply a model instance to a nested object by setting the key and the model in relations method.

    If the backend responds with:

    // response from API for /posts/1
    {
      title: 'My title'
      body: 'Some text here',
      user: {
        firstName: 'John',
        lastName: 'Doe'
      }
    }
    

    We just need to set user to User model:

    /models/Post.js

    class Post extends Model {
      relations () {
        return {
          // Apply User model to `user` object
          user: User
        }
      }
    }
    

    It also works for collections. So if the backend responds with:

    // response from API for /comments
    {
      text: 'Some text here',
      user: {
        firstName: 'John',
        lastName: 'Doe'
      },
      replies: [
        {
          text: 'A reply here',
          user: {
            firstName: 'Joe',
            lastName: 'Doe'
          }
        },
        {
          text: 'Another reply here',
          user: {
            firstName: 'Mary',
            lastName: 'Doe'
          },
          replies: [
            {
              text: 'Yes, this is the reply of the reply!',
              user: {
                firstName: 'Max',
                lastName: 'Doe'
              }
            }
          ]
        }
      ]
    }
    

    Then we just need to set user to User model and replies to Comment model:

    /models/Comment.js

    class Comment extends Model {
      relations () {
        return {
          // Apply User model to `user` object
          user: User,
          // Apply Comment model to each object of `replies` array
          replies: Comment
        }
      }
    }
    
    Source code(tar.gz)
    Source code(zip)
  • 1.5.2(May 15, 2020)

    • Update all dependencies
    • Small fix on README @manniL
    • Reset query string @MichMich
    • save() method makes a PUT request to the correct URL on nested object thas was fetched with find() method @taai

    Thanks to @Peter-Krebs for reviewing.

    Source code(tar.gz)
    Source code(zip)
  • 1.5.1(May 2, 2019)

  • 1.5.0(Apr 18, 2019)

    Thanks @leeovery for #61.

    Introduces new fetch style request for find() and first() methods. See README for more info.

    let user = await User.$find(1)
    
    let user = await User.$first()
    
    Source code(tar.gz)
    Source code(zip)
  • 1.4.1(Feb 27, 2019)

  • 1.4.0(Feb 24, 2019)

    Thanks @Peter-Krebs

    The custom() method can be called with multiple arguments to build resource endpoints and hierarchies. Simply supply them in the correct order. Any combination of strings and models is possible.

        let user = new User({ id: 1 })
        let post = new Post()
    
        // GET /users/1/posts/latest
        const result = await Post.custom(user, post, 'latest').get()
    
    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Feb 18, 2019)

    Update dependencies

    Updated to latest babel and eslint features.

    Added ability to customize query parameter names

    If you need to change default values just override parametersName() on your Base Model. So, the generated query string will use this new values.

    import { Model as BaseModel } from 'vue-api-query'
    
    export default class Model extends BaseModel {
    
      parameterNames () {
        return {
          include: 'include_custom',
          filter: 'filter_custom',
          sort: 'sort_custom',
          fields: 'fields_custom',
          append: 'append_custom',
          page: 'page_custom',
          limit: 'limit_custom'
        }
      }
    }
    

    Thanks @suth https://github.com/robsontenorio/vue-api-query/pull/42

    Fix array strategy validation for SSR

    Got error on using vue-api-query with NUXT on universal mode (SSR)

    Thanks @MisterEffix https://github.com/robsontenorio/vue-api-query/pull/43

    Source code(tar.gz)
    Source code(zip)
  • 1.2.0(Nov 22, 2018)

     let user = new User({id: 1})
     let post = await user.posts().first()
     
     // Related objects go in order of their appearance in the URL.
     let comment = new Comment({text: 'for() takes multiple objects.'}).for(user, post)
      // POST /users/1/posts/1/comments
     await comment.save()
    
    Source code(tar.gz)
    Source code(zip)
  • 1.1.0(Jul 26, 2018)

    If you need to get a nested resource, without getting the parent model at first, you can do something like this.

    // GET /users/1/posts
    
    let User = new User({id: 1})
    let Post = await User.posts().get()
    
    // GET /users/1/posts/2
    let User = new User({id: 1})
    let Post = await User.posts().find(2)
    
    Source code(tar.gz)
    Source code(zip)
  • 1.0.0(Jul 16, 2018)

    • Tag 1.0.0 stable
    • for() method for creating new related objects

    Creating new related objects is easy. Just use the for() method, passing the related object.

      let post = new Post({title: 'Woo!'})  
    
      // POST /posts
      await post.save()
    
      let comment = new Comment({text: 'New one for this post'}).for(post)
    
      // POST /posts/1/comments
      await comment.save()
    
    Source code(tar.gz)
    Source code(zip)
  • 0.7.0(Jun 5, 2018)

    If you need to pass any extra param not provided by vue-api-query pattern, just use the params() method while querying:

    // GET /users?doSomething=yes&process=no
    
    let users = await User
      .params({
        doSomething: 'yes',
        process: 'no'
      })
      .get()
    

    Of course you can chain it with other methods, including on relationships.

    // GET /posts/1/comments?include=user&blah=123
    
    let comments = await post
      .comments()
      .include('user')
      .params({blah: 123})
      .get()
    
    Source code(tar.gz)
    Source code(zip)
  • 0.6.0(May 16, 2018)

  • 0.5.0(Apr 11, 2018)

  • 0.4.1(Apr 6, 2018)

  • 0.4.0(Apr 5, 2018)

  • 0.3.0(Mar 31, 2018)

  • 0.2.0(Mar 30, 2018)

Owner
Robson Tenório
Laravel, Vue, Nuxt, Electron.
Robson Tenório
Vue 2 directive to easily add AJAX requests to your application

v-fetch v-fetch is a Vue directive to add AJAX to your app without the boilerplate Summary v-fetch is a directive that adds AJAX functionality to your

Shayne Kasai 6 Mar 31, 2022
Control your API calls by using an amazing component which supports axios and vue-resource

Vue API Request Vue API Request provides a full control on your APIs, making the calls simple, fast and easy to implement. Also, your code will be cle

Felipe Gibran Eleuterio Toledo 127 Dec 10, 2022
VueJS reactive RESTful API

Vue Chimera VueJS RESTful client with reactive features. Vue-Chimera is based on axios http client library. Overview of features: Loading flags Bindin

null 166 Nov 14, 2022
Backend mocking for rapid project testing and previews

Vue-Resource-Mock This package requires no specific version of Vue but vue-resource. It works for both Vue/Vue2 as the time of this writing. Copy and

xiuxiuxiu 29 Nov 1, 2021
Solution to remove and simplify axios in components vue

Vue fast axios Solution to remove and simplify axios in components vue Dependencies: Only Vue.js 2.x Before install Before installing, you must instal

Leonardo Vilarinho 43 Apr 16, 2022
Smart asynchronous data and computed properties for vue components.

vue-async-properties Vue Component Plugin for asynchronous data and computed properties. A Marketdial Project new Vue({ props: { articleId: Numb

MarketDial 38 Jun 21, 2021
Hermes is a MITM proxy that allows HTTP, HTTPS and HTTP/2 trafic interception.

Hermes is a man-in-the-middle proxy that allows HTTP, HTTPS and HTTP/2 trafic interception, inspection and modification.

Open-Source by Veepee 29 Nov 10, 2022
Vue Axios Http - This package helps you quickly to build requests for REST API

Vue Axios Http This package helps you quickly to build requests for REST API. Move your logic and backend requests to dedicated classes.

Chantouch Sek 4 Apr 9, 2022
REST Countries API with color theme switcher is one of the Frontend Mentor challenges. It uses Composition API for Vue.js 3 and pulls data from the REST Countries API.

REST Countries API REST Countries API with color theme switcher is one of the Frontend Mentor challenges. It uses Composition API for Vue.js 3 and pul

Gizem Korkmaz 7 Sep 5, 2022
Vue Client with Axios to make CRUD requests to Rest API in that

Vue Axios example with Rest API Vue Client with Axios to make CRUD requests to Rest API in that: Vue Axios GET request: get all Tutorials, get Tutoria

ivandjoh 2 Apr 4, 2022
Rest-api-client - Easily accessible REST API client available on your favorite browser

REST API Client Website: https://l23de.github.io/rest-api-client/ Inspirations t

Lester Huang 0 Jan 1, 2022
Vue.js library for handling REST service requests and model definitions.

Vue service model Vue.js Library for handling REST service requests with caching, aggregation and model definitions. Features Define models and easily

null 19 Jan 15, 2022
Rick-and-morty-vue - App web de Rick And Morty utilizando Vue 3 - Composition API, Vuex, API Rest

Rick And Morty utilizando Vue 3 - Composition API, Vuex, API Rest Project setup npm install Compiles and hot-reloads for development npm run serve C

Luis Timaná 0 Jan 1, 2022
An elegant way to convert quantities between different units.

convert-units A handy utility for converting between quantities in different units. Installation npm install convert-units --save # beta builds are al

null 646 Dec 27, 2022
eCommerce web app build using VueJs, TailwindCSS, Python, Django and Django Rest Framework.

eCommerce web app build using VueJs, TailwindCSS, Python, Django and Django Rest Framework.

Ajay Patel 2 Jun 14, 2022
A terminating Apollo Link for Apollo Client that allows FileList, File, Blob instances within query or mutation variables and sends GraphQL multipart requests

A terminating Apollo Link for Apollo Client that allows FileList, File, Blob instances within query or mutation variables and sends GraphQL multipart requests

chandu 0 Sep 1, 2020
A simple weather app build with laravel, vuejs, algolia places api and open-weather api

A simple weather app build with laravel, vuejs, algolia places api and open-weather api

Susmoy Sen Gupta 11 Dec 4, 2022
A simple Vue blog template that displays posts from any WordPress REST API endpoint.

WP Vue This is just a simple Vue application (scaffolded using the Vue CLI) that pulls posts from a WordPress REST API endpoint. Clone or fork this su

Alex MacArthur 448 Dec 27, 2022
A simple Vue blog template that displays posts from any WordPress REST API endpoint.

WP Vue This is just a simple Vue application (scaffolded using the Vue CLI) that pulls posts from a WordPress REST API endpoint. Clone or fork this su

Alex MacArthur 448 Dec 27, 2022
A new, beautiful and the-way-it-supposed-to-be way to review Lanyard

A new, beautiful and the-way-it-supposed-to-be way to review Lanyard, its community projects and websites that use Lanyard in one place!

EGGSY 40 Jan 1, 2023