### Installing Frappe JS SDK Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md These snippets show how to install the frappe-js-sdk library using either npm or yarn, the two most common package managers for Node.js and frontend projects. This is the first step before using the SDK. ```bash npm install frappe-js-sdk ``` ```bash yarn add frappe-js-sdk ``` -------------------------------- ### Initializing Auth Library Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to get an instance of the authentication library from the initialized FrappeApp object. This `auth` object provides methods for user authentication operations. ```javascript const auth = frappe.auth() ``` -------------------------------- ### Initializing Database Library Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to get an instance of the database library from the initialized FrappeApp object. This `db` object provides methods for interacting with Frappe DocTypes and documents. ```javascript const db = frappe.db(); ``` -------------------------------- ### Initializing FrappeApp (Cookie/Standard Auth) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet demonstrates the basic initialization of the FrappeApp class. You need to import FrappeApp and pass the URL of your Frappe backend. This setup is typically used for cookie-based authentication. ```javascript import { FrappeApp } from 'frappe-js-sdk'; //Add your Frappe backend's URL const frappe = new FrappeApp('https://test.frappe.cloud'); ``` -------------------------------- ### Fetching List of Documents Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md These snippets show how to fetch a list of documents for a given DocType. The first example shows basic fetching, while the second demonstrates using the optional second argument for filtering, sorting, limiting, pagination, and other query options. ```javascript db.getDocList('DocType') .then((docs) => console.log(docs)) .catch((error) => console.error(error)); ``` ```javascript db.getDocList('DocType', { /** Fields to be fetched */ fields: ['name', 'creation'], /** Filters to be applied - SQL AND operation */ filters: [['creation', '>', '2021-10-09']], /** Filters to be applied - SQL OR operation */ orFilters: [], /** Fetch from nth document in filtered and sorted list. Used for pagination */ limit_start: 5, /** Number of documents to be fetched. Default is 20 */ limit: 10, /** Sort results by field and order */ orderBy: { field: 'creation', order: 'desc', }, /** Group the results by particular field */ groupBy: 'name', /** Fetch documents as a dictionary */ asDict: false, }) .then((docs) => console.log(docs)) .catch((error) => console.error(error)); ``` -------------------------------- ### Setting Field Values of a Document Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md These snippets show how to set specific field values on an existing document. You can set a single field's value (first example) or multiple fields using an object (second example). It returns a Promise resolving with the updated document. ```javascript /** Set value of a single field **/ db.setValue('My Custom DocType', 'Test', 'Field_Name', 'Value') .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` ```javascript /** Set values of multiple fields **/ db.setValue('My Custom DocType', 'Test', {'Field_Name1':"Value1",'Field_Name2':"Value2"}) .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` -------------------------------- ### Making Frappe Call GET Request (JavaScript) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md Demonstrates making a GET request to a Frappe endpoint (`frappe.desk.search_link`) with specific parameters. The `searchParams` object contains the data passed to the endpoint. It uses Promises (`.then()`, `.catch()`) to handle the asynchronous response or potential errors. ```javascript const searchParams = { doctype: 'Currency', txt: 'IN', }; call .get('frappe.desk.search_link', searchParams) .then((result) => console.log(result)) .catch((error) => console.error(error)); ``` -------------------------------- ### Getting Field Values of a Document Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md These snippets demonstrate fetching specific field values from documents. You can fetch a single field (first example) or multiple fields (second example) based on DocType and filters. It returns a Promise resolving with an object containing the requested fields and values. ```javascript /** Get single field value **/ db.getValue('My Custom DocType', 'Field_Name', [['Filter1', '=', 'Value1'],['Filter2', '=', 'Value2']]) .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` ```javascript /** Get multiple field values **/ db.getValue('My Custom DocType', ['Field_Name1', 'Field_Name2'], [['Filter1', '=', 'Value1'],['Filter2', '=', 'Value2']]) .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` -------------------------------- ### Fetching Document Count Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to get the total count of documents for a given DocType, optionally applying filters. It returns a Promise resolving with the document count. ```javascript const filters = [['creation', '>', '2021-10-09']]; const useCache = true; /** Default is false - Optional **/ const debug = false; /** Default is false - Optional **/ db.getCount('DocType', filters, cache, debug) .then((count) => console.log(count)) .catch((error) => console.error(error)); ``` -------------------------------- ### Getting Logged-in User Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to fetch the currently logged-in user's ID. It makes an API call to the `/api/method/frappe.auth.get_logged_user` endpoint and returns a Promise resolving with the user ID. ```javascript auth .getLoggedInUser() .then((user) => console.log(`User ${user} is logged in.`)) .catch((error) => console.error(error)); ``` -------------------------------- ### Getting Field Value from Single DocType Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet demonstrates fetching a specific field value from a 'Single' type DocType (a DocType that has only one record system-wide). You provide the Single DocType name and the field name. It returns a Promise resolving with the value of the requested field. ```javascript db.getSingleValue('My Custom Single DocType', 'Field_Name') .then((response) => console.log(response.message)) // Message will reflect the value of the field. .catch((error) => console.error(error)); ``` -------------------------------- ### Initialising Frappe File Client (TypeScript) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md Initializes a new instance of the Frappe File client. This client is specifically designed for handling file upload operations within the Frappe framework. Requires the Frappe JS SDK to be loaded and the `frappe` object available globally. ```typescript const file = frappe.file(); ``` -------------------------------- ### Logging in User Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet demonstrates logging in a user using a username and password. It calls the Frappe `/api/method/login` endpoint. The method returns a Promise that resolves on success or rejects on error. ```javascript auth .loginWithUsernamePassword({ username: 'admin', password: 'my-password' }) .then((response) => console.log('Logged in')) .catch((error) => console.error(error)); ``` -------------------------------- ### Initializing Frappe Call Client (TypeScript) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md Initializes a new instance of the Frappe Call client. This client is used for making various types of API requests to the Frappe backend. Requires the Frappe JS SDK to be loaded and the `frappe` object available globally. ```typescript const call = frappe.call(); ``` -------------------------------- ### Initializing FrappeApp (Token Auth) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to initialize the FrappeApp for token-based authentication (like OAuth bearer tokens or API key/secret). You enable `useToken`, provide a function to retrieve the token, and specify the token type ('Bearer' or 'token'). ```javascript import { FrappeApp } from "frappe-js-sdk"; const frappe = new FrappeApp("https://test.frappe.cloud", { useToken: true, // Pass a custom function that returns the token as a string - this could be fetched from LocalStorage or auth providers like Firebase, Auth0 etc. token: getTokenFromLocalStorage(), // This can be "Bearer" or "token" type: "Bearer" }) ``` -------------------------------- ### Creating a Document Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet demonstrates how to create a new document in Frappe. You provide the DocType name and an object containing the field values for the new document. It returns a Promise resolving with the newly created document. ```javascript db.createDoc('My Custom DocType', { name: 'Test', test_field: 'This is a test field', }) .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` -------------------------------- ### Uploading File with Progress Callback (JavaScript) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md Shows how to upload a file using the Frappe File client's `uploadFile` method. It includes an object `fileArgs` for specifying details about the file and its association with a document. The snippet also demonstrates providing a callback function to track upload progress and uses Promises for completion and error handling. ```javascript const myFile; //Your File object const fileArgs = { /** If the file access is private then set to TRUE (optional) */ "isPrivate": true, /** Folder the file exists in (optional) */ "folder": "Home", /** File URL (optional) */ "file_url": "", /** Doctype associated with the file (optional) */ "doctype": "User", /** Docname associated with the file (mandatory if doctype is present) */ "docname": "Administrator", /** Field in the document **/ "fieldname": "image" } file.uploadFile( myFile, fileArgs, /** Progress Indicator callback function **/ (completedBytes, totalBytes) => console.log(Math.round((completedBytes / totalBytes) * 100), " completed") ) .then(() => console.log("File Upload complete")) .catch(e => console.error(e)) ``` -------------------------------- ### Fetching Document by Name Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet demonstrates fetching a single document by its DocType and name. It returns a Promise resolving with the document object or rejecting with an error. ```javascript db.getDoc('DocType', 'My DocType Name') .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` -------------------------------- ### Submitting a Document Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to submit a document that is currently in a draft state. You pass the document object to the `submit` method. It returns a Promise resolving with the submitted document. ```javascript db.submit(doc) .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` -------------------------------- ### Making Frappe Call PUT Request (JavaScript) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md Illustrates making a PUT request to a Frappe endpoint (`frappe.client.set_value`) using the Frappe Call client. The `updatedFields` object contains the data to be sent with the request. Asynchronous handling is done with `.then()` and `.catch()`. ```javascript const updatedFields = { doctype: 'User', name: 'Administrator', fieldname: 'interest', value: 'Frappe Framework, ERPNext', }; call .put('frappe.client.set_value', updatedFields) .then((result) => console.log(result)) .catch((error) => console.error(error)); ``` -------------------------------- ### Making Frappe Call POST Request (JavaScript) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md Shows how to make a POST request to a Frappe endpoint (`frappe.client.set_value`) with the provided `updatedFields` object as parameters. It uses Promises to handle the successful response or catch any errors during the request. ```javascript const updatedFields = { doctype: 'User', name: 'Administrator', fieldname: 'interest', value: 'Frappe Framework, ERPNext', }; call .post('frappe.client.set_value', updatedFields) .then((result) => console.log(result)) .catch((error) => console.error(error)); ``` -------------------------------- ### Updating a Document Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to update an existing document. You provide the DocType name, the name of the document to update, and an object containing the fields and their new values. It returns a Promise resolving with the updated document. ```javascript db.updateDoc('My Custom DocType', 'Test', { test_field: 'This is an updated test field.', }) .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` -------------------------------- ### Renaming a Document Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to rename an existing document. You provide the DocType name, the current name, and the new name. It returns a Promise resolving with a response message indicating the rename status. ```javascript db.renameDoc('My Custom DocType', 'Old Name', 'New Name') .then((response) => console.log(response.message)) // The message will reflect the updated document name. .catch((error) => console.error(error)); ``` -------------------------------- ### Logging out User Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet demonstrates logging out the current user. It makes an API call to the `/api/method/logout` endpoint. The method returns a Promise that resolves upon successful logout. ```javascript auth .logout() .then(() => console.log('Logged out.')) .catch((error) => console.error(error)); ``` -------------------------------- ### Requesting Password Reset Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet shows how to initiate the forget password process. It sends a request to the Frappe backend to send a password reset link to the specified email address. ```javascript auth .forgetPassword('example@example.com') .then(() => console.log('Password Reset Email Sent!')) .catch(() => console.error("We couldn't find your account.")); ``` -------------------------------- ### Deleting a Document Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet demonstrates how to delete a document. You provide the DocType name and the name of the document to delete. It returns a Promise resolving with a response message, which is typically 'ok' on success. ```javascript db.deleteDoc('My Custom DocType', 'Test') .then((response) => console.log(response.message)) // Message will be "ok" .catch((error) => console.error(error)); ``` -------------------------------- ### Making Frappe Call DELETE Request (JavaScript) Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md Demonstrates making a PUT request to the Frappe delete endpoint (`frappe.client.delete`) using the Frappe Call client. The `documentToBeDeleted` object specifies the document intended for deletion. The request is handled asynchronously using Promises. ```javascript const documentToBeDeleted = { doctype: 'Tag', name: 'Random Tag', }; call .put('frappe.client.delete', documentToBeDeleted) .then((result) => console.log(result)) .catch((error) => console.error(error)); ``` -------------------------------- ### Updating Document with TypeScript Types Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet illustrates how to use TypeScript interfaces to provide type checking for document data when using methods like `updateDoc`. It ensures that the data object conforms to the specified `TestDoc` interface, improving code safety and readability. ```typescript interface TestDoc { test_field: string; } db.updateDoc('My Custom DocType', 'Test', { test_field: 'This is an updated test field.', }); ``` -------------------------------- ### Cancelling a Document Source: https://github.com/the-commit-company/frappe-js-sdk/blob/main/README.md This snippet demonstrates how to cancel a submitted document. You provide the DocType name and the name of the document to cancel. It returns a Promise resolving with the cancelled document. ```javascript db.cancel('My Custom DocType', 'Test') .then((doc) => console.log(doc)) .catch((error) => console.error(error)); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.