CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-vue-resource

The HTTP client for Vue.js providing services for making web requests and handling responses using XMLHttpRequest or JSONP

Pending
Overview
Eval results
Files

resources.mddocs/

RESTful Resources

Resource abstraction for RESTful APIs providing predefined CRUD operations with URL templating, parameter binding, and customizable actions.

Capabilities

Resource Creation

Create a resource object with predefined methods for common RESTful operations.

/**
 * Create a RESTful resource with predefined actions
 * @param url - URL template with optional parameters (e.g., '/users{/id}')
 * @param params - Default parameters for URL substitution
 * @param actions - Custom actions to extend default resource methods
 * @param options - Default HTTP options for all resource methods
 * @returns Resource object with CRUD methods
 */
function $resource(
  url: string, 
  params?: object, 
  actions?: object, 
  options?: HttpOptions
): ResourceMethods;

interface ResourceMethods {
  get: ResourceMethod;
  save: ResourceMethod;
  query: ResourceMethod;
  update: ResourceMethod;
  remove: ResourceMethod;
  delete: ResourceMethod;
}

interface ResourceMethod {
  (params?: any, data?: any): Promise<HttpResponse>;
  (params?: any): Promise<HttpResponse>;
  (): Promise<HttpResponse>;
}

Usage Examples:

// Basic resource
const UserResource = this.$resource('/api/users{/id}');

// Resource with default parameters
const UserResource = this.$resource('/api/users{/id}', {id: '@id'});

// Resource with custom actions
const UserResource = this.$resource('/api/users{/id}', {}, {
  activate: {method: 'POST', url: '/api/users{/id}/activate'},
  search: {method: 'GET', url: '/api/users/search'}
});

// Resource with default options
const UserResource = this.$resource('/api/users{/id}', {}, {}, {
  headers: {'Authorization': 'Bearer token'}
});

Default Resource Actions

All resources come with six predefined actions for common CRUD operations.

// Default actions available on all resources
const defaultActions = {
  get: { method: 'GET' },
  save: { method: 'POST' },
  query: { method: 'GET' },
  update: { method: 'PUT' },
  remove: { method: 'DELETE' },
  delete: { method: 'DELETE' }
};

Usage Examples:

const UserResource = this.$resource('/api/users{/id}');

// GET /api/users/1
UserResource.get({id: 1}).then(response => {
  console.log('User:', response.body);
});

// GET /api/users (query for multiple)
UserResource.query().then(response => {
  console.log('All users:', response.body);
});

// POST /api/users (create new)
UserResource.save({name: 'John', email: 'john@example.com'}).then(response => {
  console.log('Created user:', response.body);
});

// POST /api/users (create with params and data)
UserResource.save({}, {name: 'John', email: 'john@example.com'}).then(response => {
  console.log('Created user:', response.body);
});

// PUT /api/users/1 (update existing)
UserResource.update({id: 1}, {name: 'John Updated'}).then(response => {
  console.log('Updated user:', response.body);
});

// DELETE /api/users/1
UserResource.remove({id: 1}).then(response => {
  console.log('User deleted');
});

// DELETE /api/users/1 (alias for remove)
UserResource.delete({id: 1}).then(response => {
  console.log('User deleted');
});

URL Templates

Resources support URI templates for dynamic URL construction with parameter substitution.

Usage Examples:

// Simple parameter substitution
const UserResource = this.$resource('/api/users/{id}');
UserResource.get({id: 123}); // GET /api/users/123

// Optional parameters with braces
const UserResource = this.$resource('/api/users{/id}');
UserResource.query(); // GET /api/users
UserResource.get({id: 123}); // GET /api/users/123

// Multiple parameters
const PostResource = this.$resource('/api/users/{userId}/posts{/postId}');
PostResource.query({userId: 1}); // GET /api/users/1/posts
PostResource.get({userId: 1, postId: 5}); // GET /api/users/1/posts/5

// Default parameters with @ prefix (extracts from data)
const UserResource = this.$resource('/api/users/{id}', {id: '@id'});
UserResource.update({id: 1, name: 'John'}); // PUT /api/users/1

Custom Actions

Extend resources with custom actions for specialized endpoints.

interface ResourceAction {
  method: string;
  url?: string;
  params?: object;
  headers?: object;
  [key: string]: any;
}

Usage Examples:

// Resource with custom actions
const UserResource = this.$resource('/api/users{/id}', {}, {
  // Custom action with different URL
  activate: {
    method: 'POST', 
    url: '/api/users{/id}/activate'
  },
  
  // Custom action with different method
  search: {
    method: 'GET',
    url: '/api/users/search'
  },
  
  // Custom action with additional parameters
  resetPassword: {
    method: 'POST',
    url: '/api/users{/id}/reset-password',
    params: {sendEmail: true}
  }
});

// Use custom actions
UserResource.activate({id: 1}).then(response => {
  console.log('User activated');
});

UserResource.search({q: 'john'}).then(response => {
  console.log('Search results:', response.body);
});

UserResource.resetPassword({id: 1}).then(response => {
  console.log('Password reset initiated');
});

Parameter Binding

Resources support flexible parameter binding for URL construction and data extraction.

Usage Examples:

// Default parameter extraction from data
const UserResource = this.$resource('/api/users/{id}', {id: '@id'});

// When calling save/update, id is extracted from data object
const userData = {id: 1, name: 'John', email: 'john@example.com'};
UserResource.update(userData); // PUT /api/users/1

// Explicit parameters override extracted values
UserResource.update({id: 2}, userData); // PUT /api/users/2

// Complex parameter extraction
const PostResource = this.$resource('/api/users/{userId}/posts/{id}', {
  userId: '@author.id',
  id: '@id'
});

const postData = {
  id: 5,
  title: 'My Post',
  author: {id: 1, name: 'John'}
};
PostResource.update(postData); // PUT /api/users/1/posts/5

Error Handling

Resource methods return promises that can be handled with standard promise patterns.

Usage Examples:

const UserResource = this.$resource('/api/users{/id}');

// Promise-based error handling
UserResource.get({id: 999}).then(response => {
  console.log('User found:', response.body);
}, response => {
  if (response.status === 404) {
    console.log('User not found');
  } else {
    console.error('Error:', response.status, response.statusText);
  }
});

// Async/await error handling
async function getUser(id) {
  try {
    const response = await UserResource.get({id});
    return response.body;
  } catch (response) {
    if (response.status === 404) {
      return null;
    }
    throw new Error(`Failed to get user: ${response.statusText}`);
  }
}

Global Resource Configuration

Configure default behavior for all resources.

// Default resource actions (can be overridden)
Vue.resource.actions = {
  get: { method: 'GET' },
  save: { method: 'POST' },
  query: { method: 'GET' },
  update: { method: 'PUT' },
  remove: { method: 'DELETE' },
  delete: { method: 'DELETE' }
};

Usage Examples:

// Add a custom action to all resources
Vue.resource.actions.patch = {method: 'PATCH'};

// Now all resources have a patch method
const UserResource = this.$resource('/api/users{/id}');
UserResource.patch({id: 1}, {name: 'Updated Name'});

Types

interface ResourceMethods {
  /** Get a single resource by ID */
  get: ResourceMethod;
  /** Create a new resource (POST) */
  save: ResourceMethod;
  /** Query for multiple resources (GET collection) */
  query: ResourceMethod;
  /** Update an existing resource (PUT) */
  update: ResourceMethod;
  /** Delete a resource */
  remove: ResourceMethod;
  /** Delete a resource (alias for remove) */
  delete: ResourceMethod;
}

interface ResourceMethod {
  /** Call with parameters and data */
  (params: any, data?: any): Promise<HttpResponse>;
  /** Call with parameters only */
  (params: any): Promise<HttpResponse>;
  /** Call without parameters */
  (): Promise<HttpResponse>;
}

interface ResourceAction {
  /** HTTP method for the action */
  method: string;
  /** URL template for the action (optional, uses resource URL if not specified) */
  url?: string;
  /** Default parameters for the action */
  params?: object;
  /** Default headers for the action */
  headers?: object;
  /** Additional action configuration */
  [key: string]: any;
}

interface ResourceActions {
  get: ResourceAction;
  save: ResourceAction;
  query: ResourceAction;
  update: ResourceAction;
  remove: ResourceAction;
  delete: ResourceAction;
}

Install with Tessl CLI

npx tessl i tessl/npm-vue-resource

docs

http-client.md

index.md

interceptors.md

promise-service.md

resources.md

url-processing.md

tile.json