Frappe JS SDK

repository·main·Indexed 41 days ago

https://github.com/frappe/frappe-js-sdk

A TypeScript/JavaScript client library for the Frappe Framework REST API (version 1.14.1). It provides high-level abstractions for authentication via FrappeAuth, database CRUD operations and document lifecycle management via FrappeDB, and custom API method calls through the FrappeCall class.

Tokens
8.9K
Snippets
37
Records
39
Agent score
51%

What's inside Frappe JS SDK

  1. Use Frappe with TypeScript

    main

    The library provides built-in type support. You can pass a generic type to methods like updateDoc<T> to enforce schema.

    Additionally, all document responses are returned as an intersection of the specified type and the FrappeDoc<T> type, which includes standard Frappe fields:

    • name: Primary key
    • owner: Creator
    • creation: ISO timestamp
    • modified: ISO timestamp
    • modified_by: Last modifier
    • docstatus: 0 (Saved), 1 (Submitted), 2 (Cancelled)
    • idx: Index
    interface TestDoc {
      test_field: string;
    }
    
    // Enforcing types on database calls
    db.updateDoc<TestDoc>('My Custom DocType', 'Test', {
      test_field: 'This is an updated test field.',
    });
  2. Install frappe-js-sdk

    main

    Install the library using npm or yarn to use it in your TypeScript/JavaScript project.

    npm install frappe-js-sdk

    or

    yarn add frappe-js-sdk
  3. Access Frappe SDK modules

    main

    The SDK is organized into several functional modules that are all exported from the main entry point. You can access these directly via the FrappeApp instance or by importing the specific modules if they are exported separately:

    • Authentication: Manage user sessions and login/logout.
    • Database: Perform CRUD operations on DocTypes.
    • File: Handle file uploads and management.
    • Call: Execute RPC calls to server-side functions.
  4. Upload files

    main

    Use frappe.file() to upload files. The uploadFile method accepts a File object, an options object, and an optional progress callback.

    Options object (fileArgs):

    • isPrivate: (boolean) Set to true if the file should be private.
    • folder: (string) The folder name.
    • file_url: (string) The file URL.
    • doctype: (string) The DocType associated with the file.
    • docname: (string) The name of the document associated with the file (mandatory if doctype is present).
    • fieldname: (string) The field in the document where the file is attached.
    const file = frappe.file();
    const myFile = new File([''], 'example.txt', { type: 'text/plain' });
    
    const fileArgs = {
      "isPrivate": true,
      "doctype": "User",
      "docname": "Administrator",
      "fieldname": "image"
    };
    
    file.uploadFile(
      myFile,
      fileArgs,
      (completedBytes, totalBytes) => console.log(Math.round((completedBytes / totalBytes) * 100) + '% completed')
    ).then(() => console.log("File Upload complete"));
  5. Initialise FrappeApp

    main

    To use the library, create an instance of FrappeApp with your Frappe backend URL.

    For standard cookie-based authentication, pass only the URL. For token-based authentication (OAuth bearer tokens or API key/secret pairs), provide an options object with useToken: true, a token function that returns the token string, and the type (either "Bearer" or "token").

    import { FrappeApp } from 'frappe-js-sdk';
    
    // Standard initialization
    const frappe = new FrappeApp('https://test.frappe.cloud');
    
    // Token-based initialization
    const frappe = new FrappeApp("https://test.frappe.cloud", {
        useToken: true,
        token: getTokenFromLocalStorage(),
        type: "Bearer"
    });
  6. Perform database operations

    main

    Access database methods via frappe.db().

    Document Operations

    • getDoc(doctype, name): Fetch a single document.
    • getDocList(doctype, options): Fetch a list of documents. Options include fields, filters (AND), orFilters (OR), limit_start, limit, orderBy (object with field and order), groupBy, and asDict.
    • getCount(doctype, filters, debug): Get the count of documents matching filters.
    • createDoc(doctype, fields): Create a new document.
    • updateDoc(doctype, name, fields): Update an existing document.
    • deleteDoc(doctype, name): Delete a document.
    • renameDoc(doctype, old_name, new_name): Rename a document.
    • submit(doc): Submit a document.
    • cancel(doctype, name): Cancel a submitted document.

    Field Operations

    • getValue(doctype, field, filters): Get a single field or an array of fields.
    • setValue(doctype, name, field, value): Set a single field or multiple fields via an object.
    • getSingleValue(doctype, field): Retrieve a field value from a Single-type doctype.
    const db = frappe.db();
    
    // Fetch list with filters and pagination
    db.getDocList('DocType', {
      fields: ['name', 'creation'],
      filters: [['creation', '>', '2021-10-09']],
      limit: 10,
      orderBy: { field: 'creation', order: 'desc' }
    });
    
    // Update a document
    db.updateDoc('My Custom DocType', 'Test', { test_field: 'new value' });
    
    // Set multiple fields
    db.setValue('My Custom DocType', 'Test', { 'Field1': 'Val1', 'Field2': 'Val2' });
  7. Make custom API calls

    main

    Use frappe.call() to interact with whitelisted (@frappe.whitelist()) backend methods. Supported HTTP methods include:

    • get(method, params)
    • post(method, params)
    • put(method, params)
    • delete(method, params)
    const call = frappe.call();
    
    // GET request
    call.get('frappe.desk.search_link', { doctype: 'Currency', txt: 'IN' });
    
    // POST request
    call.post('frappe.client.set_value', { doctype: 'User', name: 'Administrator', fieldname: 'interest', value: 'Frappe' });
    
    // PUT request
    call.put('frappe.client.set_value', { doctype: 'User', name: 'Administrator', fieldname: 'interest', value: 'Frappe' });
    
    // DELETE request
    call.delete('frappe.client.delete', { doctype: 'Tag', name: 'Random Tag' });
  8. Manage user authentication

    main

    Access authentication methods via frappe.auth(). Supported operations include:

    • loginWithUsernamePassword({ username, password }): Logs in a user via /api/method/login.
    • getLoggedInUser(): Retrieves the currently logged-in user via /api/method/frappe.auth.get_logged_user.
    • logout(): Logs out the user via /api/method/logout.
    • forgetPassword(email): Sends a password reset link to the specified email.
    const auth = frappe.auth();
    
    // Login
    auth.loginWithUsernamePassword({ username: 'admin', password: 'my-password' })
      .then(() => console.log('Logged in'));
    
    // Get User
    auth.getLoggedInUser()
      .then((user) => console.log(`User ${user} is logged in.`));
    
    // Logout
    auth.logout()
      .then(() => console.log('Logged out.'));
    
    // Forget Password
    auth.forgetPassword('example@example.com')
      .then(() => console.log('Password Reset Email Sent!'));
  9. Set specific field values

    main

    The setValue method allows you to update a specific field on a document without sending the entire document object.

    setValue<T>(doctype: string, name: string, fieldname: string | object, value?: any): Promise<FrappeDoc<T>>

    • If fieldname is a string, value is the new value.
    • If fieldname is an object (mapping fields to values), the value parameter is ignored.
    // Set a single field
    await db.setValue('Task', 'TASK-001', 'status', 'Completed');
    
    // Set multiple fields via an object
    await db.setValue('Task', 'TASK-001', { status: 'Completed', priority: 'High' });
  10. Use FrappeFileUpload to upload files

    main

    The FrappeFileUpload class manages file transfers to a Frappe backend. It uses FormData to send files and supports progress tracking via an onProgress callback.

    Constructor Parameters

    • appURL: The URL of your Frappe App instance.
    • axios: An AxiosInstance used for the HTTP requests.
    • useToken (optional): Boolean indicating if token-based authentication should be used.
    • token (optional): A function that returns the authentication token string.
    • tokenType (optional): Either 'Bearer' or 'token'.
    • customHeaders (optional): An object containing custom headers to be included in the request.
    import { Axios } from 'axios';
    import { FrappeFileUpload } from 'frappe-js-sdk';
    
    const axiosInstance = Axios.create();
    const fileUploader = new FrappeFileUpload(
      'https://your-frappe-app.com',
      axiosInstance,
      true,
      () => 'your-token-here',
      'Bearer'
    );
    
    // Usage example
    const file = new File(['content'], 'example.txt', { type: 'text/plain' });
    const args = {
      isPrivate: true,
      doctype: 'Task',
      docname: 'TASK-001',
      fieldname: 'attachment',
    };
    
    const uploadedFile = await fileUploader.uploadFile(file, args, (bytesUploaded, totalBytes) => {
      console.log(`Uploaded ${bytesUploaded} of ${totalBytes} bytes`);
    });
  11. Retrieve specific values and counts

    main

    Use these specialized methods for lightweight data retrieval:

    getCount

    getCount<T>(doctype: string, filters?: Filter<T>[], debug?: boolean): Promise<number> Returns the number of documents matching the filters.

    getValue

    getValue<T>(doctype: string, fieldname?: FieldName, filters?: Filter<T>[], asDict?: boolean, debug?: boolean, parent?: string | null): Promise<T> Retrieves specific field values. Can be used to fetch child table records by providing a parent doctype.

    getSingleValue

    getSingleValue<T>(doctype: string, field: string): Promise<T> Retrieves a field value from a Single Doctype.

    // Get count of open tasks
    const count = await db.getCount('Task', [['status', '=', 'Open']]);
    
    // Get a specific field value
    const title = await db.getValue('Task', 'title', [['name', '=', 'TASK-001']]);
    
    // Get value from a Single Doctype
    const siteName = await db.getSingleValue('System Settings', 'site_name');
  12. Access SDK modules via FrappeApp methods

    main

    After initializing FrappeApp, use its methods to obtain instances of the core functional modules. Each module shares the same underlying configuration (URL, Axios instance, and authentication settings) provided during initialization.

    • app.auth(): Returns a FrappeAuth instance for managing authentication.
    • app.db(): Returns a FrappeDB instance for database operations.
    • app.file(): Returns a FrappeFileUpload instance for handling file uploads.
    • app.call(): Returns a FrappeCall instance for executing Frappe method calls.
    const app = new FrappeApp('https://your-frappe-site.com');
    
    const auth = app.auth();
    const db = app.db();
    const file = app.file();
    const call = app.call();