### Maka-Rest Quick Start Example Source: https://github.com/maka-io/maka-rest/blob/master/README.md A basic example demonstrating how to set up and use Maka-Rest to define API routes for GET and DELETE operations on 'articles'. It includes collection definitions, API initialization with options, and route configuration with authentication and role-based access control. ```javascript Items = new Mongo.Collection('items'); Articles = new Mongo.Collection('articles'); if (Meteor.isServer) { // Global API configuration const Api = new MakaRest({ prettyJson: true }); // Maps to: /api/articles/:id Api.addRoute('articles/:id', {authRequired: true}, { get(context) { return Articles.findOne(context.urlParams.id); }, delete: { roleRequired: ['author', 'admin'], action() { if (Articles.remove(this.urlParams.id)) { return {status: 'success', data: {message: 'Article removed'}; } return { statusCode: 404, body: {status: 'fail', message: 'Article not found'} }; } } }); } ``` -------------------------------- ### Install Maka-Rest Source: https://github.com/maka-io/maka-rest/blob/master/README.md Instructions for installing the Maka-Rest package using either the Meteor package manager or the maka-cli. ```bash > meteor add maka:rest ``` ```bash > maka add maka:rest ``` -------------------------------- ### MakaRest Sample Configuration Source: https://github.com/maka-io/maka-rest/blob/master/README.md Provides a comprehensive example of a MakaRest configuration, including API path, authentication, default headers, JSON formatting, and versioning. Note: This configuration is for demonstration purposes only. ```javascript new MakaRest({ apiPath: 'my-api/', auth: { token: 'auth.apiKey', user: function () { return { userId: this.request.headers['user-id'], token: this.request.headers['login-token'] }; } }, defaultHeaders: { 'Content-Type': 'application/json' }, prettyJson: true, version: 'v1' }); ``` -------------------------------- ### MakaRest API Versioning Example Source: https://github.com/maka-io/maka-rest/blob/master/README.md Demonstrates how to configure MakaRest with different API versions, affecting the base URL path for routes. ```javascript ApiV1 = new MakaRest({ apiPath: 'my-api/', version: 'v1' }); ApiV2 = new MakaRest({ apiPath: 'my-api/', version: 'v2' }); ``` -------------------------------- ### Version API with Maka-Rest (JavaScript) Source: https://github.com/maka-io/maka-rest/blob/master/README.md Configure and add routes for different API versions using Maka-Rest. This example shows setting up 'v1' and 'v2' with distinct configurations and route handlers. ```javascript var ApiV1 = new MakaRest({ version: 'v1', prettyJson: true }); // Maps to api/v1/custom ApiV1.addRoute('custom', { get: function () { return 'get something'; } }); // Configure another version of the API (with a different set of config options if needed) var ApiV2 = new MakaRest({ version: 'v2', enableCors: false }); // Maps to api/v2/custom (notice the different return value) ApiV2.addRoute('custom', { get: function () { return { status: 'success', data: 'get something different' }; } }); ``` -------------------------------- ### Consume Maka-Rest API with cURL (Bash) Source: https://github.com/maka-io/maka-rest/blob/master/README.md Example of consuming a Maka-Rest API endpoint using cURL. This demonstrates making a POST request to an endpoint with parameters. ```bash curl -d "message=Some message details" http://localhost:3000/api/articles/3/comments ``` -------------------------------- ### Maka-Rest: Access Query Parameters Source: https://github.com/maka-io/maka-rest/blob/master/README.md Shows how to access query parameters in Maka-Rest. The example demonstrates retrieving the 'q' query parameter from a URL like '/post/5?q=liked#hash_fragment' using context.queryParams. ```javascript Api.addRoute('/post/:_id', { get(context) { const id = context.urlParams._id; const query = context.queryParams; // query.q -> "liked" } }); ``` -------------------------------- ### Define API Routes with HTTP Methods Source: https://github.com/maka-io/maka-rest/blob/master/README.md Demonstrates how to define a route for 'articles' and specify different authentication requirements and actions for GET, POST, PUT, PATCH, DELETE, and OPTIONS methods. ```javascript Api.addRoute('articles', {authRequired: true}, { get: { authRequired: false, action(context) { // GET api/articles } }, post(context) { // POST api/articles }, put(context) { // PUT api/articles }, patch(context) { // PATCH api/articles }, delete(context) { // DELETE api/articles }, options(context) { // OPTIONS api/articles } }); ``` -------------------------------- ### Maka-Rest Logout Source: https://github.com/maka-io/maka-rest/blob/master/README.md Provides an example of how to log out from Maka-Rest using a curl command. The logout endpoint requires a POST request and the authentication token in the X-Auth-Token header. ```bash curl http://localhost:3000/api/logout -X POST -H "X-Auth-Token: 8zXkiThVtm3u7pE-7xacuAIrKF1VTA-WA3LRMogqiRp" ``` -------------------------------- ### Maka-Rest: Define Route with Single Parameter Source: https://github.com/maka-io/maka-rest/blob/master/README.md Demonstrates how to define a route with a single named parameter '_id' using Maka-Rest. The parameter value is accessed via context.urlParams._id within the GET endpoint function. ```javascript Api.addRoute('/post/:_id', { get(context) { const id = context.urlParams._id; // "5" } }); ``` -------------------------------- ### Running Tests in Maka-Rest Source: https://github.com/maka-io/maka-rest/blob/master/CONTRIBUTING.md This snippet shows the command to run automated tests for the Maka-Rest project. It ensures that all tests are passing before submitting changes. The output is viewed via Tinytest at http://localhost:3000. ```shell meteor test-packages ./ ``` -------------------------------- ### Interactive Git Rebase for Squashing Commits Source: https://github.com/maka-io/maka-rest/blob/master/CONTRIBUTING.md This command initiates an interactive rebase session, which can be used to squash multiple commits into a single commit. This helps maintain a clean and linear commit history. ```shell git rebase -i ``` -------------------------------- ### Git Staging with Patch Mode Source: https://github.com/maka-io/maka-rest/blob/master/CONTRIBUTING.md This command allows for interactive staging of changes, enabling developers to break down large changes into smaller, more manageable commits. This is useful for cleaning up work before committing. ```shell git add -p ``` -------------------------------- ### Maka-Rest Login with Username Source: https://github.com/maka-io/maka-rest/blob/master/README.md Demonstrates how to log in to Maka-Rest using a username and password via a curl command. The login endpoint requires a username and password in the request body. ```bash curl http://localhost:3000/api/login/ -d "username=test&password=password" ``` -------------------------------- ### Maka-Rest Authenticated API Call Source: https://github.com/maka-io/maka-rest/blob/master/README.md Demonstrates how to make an authenticated request to a Maka-Rest API endpoint. The userId and authToken must be included in the X-Auth-Token header for the request to be processed. ```bash curl -H "X-Auth-Token: f2KpRW7KeN9aPmjSZ" http://localhost:3000/api/articles/ ``` -------------------------------- ### Maka-Rest Authentication Configuration (JavaScript) Source: https://github.com/maka-io/maka-rest/blob/master/README.md Configure authentication methods for Maka-Rest. This includes setting the login type and defining callbacks for login, logout, and login failure events. ```javascript MakaRest.auth.loginType = 'default' | null MakaRest.auth.onLoggedIn((req) => {}); MakaRest.auth.onLoggedOut((req) => {}); MakaRest.auth.onLoginFailure((req, reason) => {}); ``` -------------------------------- ### Configure Redis Rate Limiting (TypeScript) Source: https://github.com/maka-io/maka-rest/blob/master/README.md Enable Redis-backed rate limiting for Maka-Rest APIs. This involves configuring the Redis client and setting rate limiting options like points, duration, and a custom key generator. ```typescript import { createClient } from 'redis'; import MakaRest from 'meteor/maka:rest'; const redisClient = createClient({ url: 'redis://localhost:6379' }); await redisClient.connect(); const Api = new MakaRest({ rateLimitOptions: { points: 5, // Max number of requests duration: 1, // Per second useRedis: true, redis: redisClient, keyGenerator: (req) => req.headers['x-auth-token'] || req.connection.remoteAddress } }); ``` -------------------------------- ### Returning Custom Response Objects Source: https://github.com/maka-io/maka-rest/blob/master/README.md Shows how to return custom response objects from an endpoint, including setting status codes, headers, and the response body. ```javascript return { statusCode: 404, headers: { 'Content-Type': 'text/plain', 'X-Custom-Header': 'custom value' }, body: 'There is nothing here!' }; ``` -------------------------------- ### Maka-Rest Login Response Source: https://github.com/maka-io/maka-rest/blob/master/README.md Illustrates the expected JSON response from the Maka-Rest login endpoint upon successful authentication. The response includes a status and data containing an authToken and timestamp. ```javascript {"status":"success","data":{"authToken":"8zXkiThVtm3u7pE-7xacuAIrKF1VTA-WA3LRMogqiRp","when":"2020-08-03T16:21:02.361Z"}} ``` -------------------------------- ### Maka-Rest: Define Route with Multiple Parameters Source: https://github.com/maka-io/maka-rest/blob/master/README.md Illustrates defining a route with multiple named parameters, '_id' and 'commentId', in Maka-Rest. Both parameter values are accessible through context.urlParams. ```javascript Api.addRoute('/post/:_id/comments/:commentId', { get(context) { const id = context.urlParams._id; // "5" const commentId = context.urlParams.commentId; // "100" } }); ``` -------------------------------- ### Manual Response Handling Source: https://github.com/maka-io/maka-rest/blob/master/README.md Illustrates how to manually handle responses within an endpoint by writing to the response object and calling `this.done()` to finalize the response. ```javascript Api.addRoute('manualResponse', { get: function () { console.log('Testing manual response'); this.response.write('This is a manual response'); this.done(); // Must call this immediately before return! } }); ``` -------------------------------- ### Maka-Rest Login with Hashed Password Source: https://github.com/maka-io/maka-rest/blob/master/README.md Shows how to log in to Maka-Rest when the password has been SHA-256 hashed on the client side. The `hashed=true` parameter indicates that the password is encrypted. ```bash curl http://localhost:3000/api/login/ -d "username=test&password=sha-256-password&hashed=true" ``` -------------------------------- ### Add Custom Interceptors (TypeScript) Source: https://github.com/maka-io/maka-rest/blob/master/README.md Implement custom interceptors in Maka-Rest for pre-route handler logic such as logging, metrics, or security checks. Interceptors are executed in the order they are added. ```typescript MakaRest.addInterceptor((req, res, next) => { console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`); next(); }); ``` ```typescript MakaRest.addInterceptor((req, res, next) => { if (req.headers['x-api-key'] !== '12345') { res.writeHead(403); res.end('Forbidden'); } else { next(); } }); ``` -------------------------------- ### Maka-Rest Authentication User Function Source: https://github.com/maka-io/maka-rest/blob/master/README.md Provides a default function for authenticating users by checking the 'X-Auth-Token' header against hashed login tokens stored in the Meteor user document. It outlines how to retrieve the token and handle successful authentication or custom error responses. ```javascript function() { return { token: Accounts._hashLoginToken(this.request.headers['x-auth-token']) }; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.