PageSourceSearch

https://suzuki.cl/scripts/utils/apiManager.js

js suzuki.cl collected 2026-09-26 14:38:13 UTC 11,220 bytes, 354 lines download raw bytes

1/**
2 * APIManager module provides methods to interact with the API for retrieving data related to brands, models, and vehicles.
3 ** importing the lib in this way:
4 *
5 * import { APIManager } from "../utils/apiManager.js";
6 *
7 * @module APIManager
8 * @version 1.1.6
9 * @author Uriel De La Hoz Orellano
10 *
11 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API|Fetch API}
12 */
13
14/**
15 * APIManager constructor function.
16 * @returns {Object} An object with methods to interact with the API.
17 */
18export const APIManager = {
19  // Base URL of the API
20  apiBaseUrl: window.location.origin,
21
22  /**
23   * Retrieves all brands from the API.
24   * @async
25   * @param {number} [skip=0] - Number of records to skip.
26   * @param {number} [take=9] - Number of records to retrieve.
27   * @returns {Promise<Object>} A promise that resolves with the data retrieved from the API.
28   */
29  async getAllBrands(skip = 0, take = 9) {
30    try {
31      const response = await fetch(
32        `${this.apiBaseUrl}/umbraco/delivery/api/v2/content?skip=${skip}&take=${take}&expand=properties[$all]&fields=properties[$all]&fetch=descendants:vehiculos&filter=contentType:marcas`,
33        {
34          headers: {
35            "Api-Key": this.apiKey,
36          },
37        }
38      );
39
40      if (!response.ok) {
41        throw new Error(
42          "An error occurred while retrieving the data. Please check the connection and try again."
43        );
44      }
45
46      const data = await response.json();
47      // console.log("getAllBrands:", data);
48      return data;
49    } catch (error) {
50      console.error("Error:", error);
51    }
52  },
53  /**
54   * Retrieves all models from the API.
55   * @async
56   * @param {number} [skip] - Number of records to skip.
57   * @param {number} [take] - Number of records to retrieve.
58   * @returns {Promise<Object>} A promise that resolves with the data retrieved from the API.
59   */
60  async getAllModels(skip, take) {
61    try {
62      const endingUrl = `/umbraco/delivery/api/v2/content?${skip ? "skip=" + skip + "&" : ""
63        }${take ? "take=" + take + "&" : ""
64        }expand=properties[$all]&fields=properties[$all]&fetch=descendants:vehiculos&filter=contentType:modelos`;
65      const response = await fetch(`${this.apiBaseUrl}${endingUrl}`, {
66        headers: {
67          "Api-Key": this.apiKey,
68        },
69      });
70
71      if (!response.ok) {
72        throw new Error(
73          "An error occurred while retrieving the data. Please check the connection and try again."
74        );
75      }
76
77      const data = await response.json();
78      // console.log("getAllModels:", data);
79      return data;
80    } catch (error) {
81      console.error("Error:", error);
82    }
83  },
84  apiKey: "Cdl7SZbG-swkp-VvdV-mFw2-b4P6-dJh6L8TJ",
85  /**
86   * Retrieves models by ID or path from the API.
87   * @async
88   * @param {string} getModelsByPath - Path of the models to retrieve.
89   * @param {number} [skip=0] - Number of records to skip.
90   * @param {number} [take=9] - Number of records to retrieve.
91   * @returns {Promise<Object>} A promise that resolves with the data retrieved from the API.
92   */
93  async getModelsByIdOrPath(getModelsByPath, skip = 0, take = 9) {
94    try {
95      if (!getModelsByPath)
96        throw new Error(`The Path "${getModelsByPath}" doesn't exists`);
97
98      const response = await fetch(
99        `${this.apiBaseUrl}/umbraco/delivery/api/v2/content?skip=${skip}&take=${take}&expand=properties[$all]&fields=properties[$all]&fetch=descendants:vehiculos&filter=contentType:modelos`,
100        {
101          headers: {
102            "Api-Key": this.apiKey,
103          },
104        }
105      );
106
107      if (!response.ok) {
108        throw new Error(
109          "An error occurred while retrieving the data. Please check the connection and try again."
110        );
111      }
112
113      const data = await response.json();
114      return data;
115    } catch (error) {
116      console.error("Error:", error);
117    }
118  },
119
120  /**
121   * Retrieves all vehicles (brands with their models) from the API.
122   * @async
123   * @param {number} [skip=0] - Number of records to skip.
124   * @param {number} [take=9] - Number of records to retrieve.
125   * @returns {Promise<Array>} A promise that resolves with the data retrieved from the API.
126   */
127  //This method is used to fetch all vehicles. It first calls getAllBrands to get a list of brands. Then, it fetches models for each brand.
128  getAllVehicles: async function (skip, take) {
129    if (!skip && !take) return [];
130    const brandsList = await this.getAllBrands(skip, take);
131    if (!brandsList) return null;
132
133    const allVehicleList = [];
134
135    brandsList.items.forEach(async (brand) => {
136      const modelsList = await this.getModelsByIdOrPath(
137        brand.route.path,
138        skip,
139        take
140      );
141      if (!modelsList) return;
142
143      brand["models"] = modelsList;
144      allVehicleList.push(brand);
145    });
146
147    return allVehicleList;
148  },
149
150  /**
151   * Retrieves all vehicles (brands with their models) from the API.
152   * @async
153   * @returns {Promise<Array>} A promise that resolves with the data retrieved from the API.
154   */
155  //overwrite the previous one , but it appears to use a different API endpoint (/api/v1/vehicles/ instead of /umbraco/delivery/api/v2/content).
156  getAllVehicles: async function () {
157    try {
158      const response = await fetch(`${this.apiBaseUrl}/api/v1/vehicles/`, {
159        headers: {
160          "Api-Key": this.apiKey,
161        },
162      });
163
164      if (!response.ok) {
165        throw new Error(
166          "An error occurred while retrieving the data. Please check the connection and try again."
167        );
168      }
169
170      const data = await response.json();
171      return data;
172    } catch (error) {
173      console.error("Error:", error);
174    }
175    return [];
176  },
177  /**
178     * Retrieves all vehicles (brands with their models) from the API.
179     * @async
180     * @param {string} [template=null] - String within the template in the Model ("Modelos") at the attribute "Tags".
181     * @returns {Promise<Array>} A promise that resolves with the data retrieved from the API.
182     */
183
184//It fetches all vehicles without the brand or model logic. It optionally accepts a template parameter to modify the URL further (/template/{template}).
185  getAllVehicles: async function (template) {
186    try {
187      let url = `${this.apiBaseUrl}/api/v1/vehicles/`;
188      if (template) url += `template/${template}`;
189
190      const response = await fetch(url, {
191        headers: {
192          "Api-Key": this.apiKey,
193        },
194      });
195
196      if (!response.ok) {
197        throw new Error(
198          "An error occurred while retrieving the data. Please check the connection and try again."
199        );
200      }
201
202      const data = await response.json();
203      // console.log("allVehicleList2:", data);
204      // console.log("allVehicleList2 URL:", url);
205      return data;
206    } catch (error) {
207      console.error("Error:", error);
208    }
209    return [];
210  },
211  /**
212   * Retrieves information about a vehicle by its unique key.
213   * If no key is provided, all vehicles are returned.
214   * @param {string} key - The unique key of the vehicle to retrieve.
215   * @returns {Promise<Object[]>} - An array of objects representing the vehicle information or an empty array if an error occurs.
216   */
217  //This method fetches a specific vehicle by its key. If no key is provided, it falls back to returning all vehicles by calling getAllVehicles.
218  getVehicleByKey: async function (key) {
219    // If no key is provided, return all vehicles
220    if (!key) return this.getAllVehicles();
221
222    try {
223      const response = await fetch(
224        `${this.apiBaseUrl}/api/v1/vehicles/${key}`,
225        {
226          headers: {
227            "Api-Key": this.apiKey,
228          },
229        }
230      );
231
232      if (!response.ok) {
233        throw new Error(
234          "An error occurred while retrieving the data. Please check the connection and try again."
235        );
236      }
237
238      const data = await response.json();
239      return data;
240    } catch (error) {
241      console.error("Error:", error);
242    }
243
244    // Return an empty array in case of error
245    return [];
246  },
247
248  /**
249   * Retrieve all blogs from the API, optionally filtered by categories, with pagination.
250   * @async
251   * @function getAllBlogs
252   * @param {string[]} [categories=[]] - An optional array of categories to filter the blogs.
253   * @param {number} [currentPage=0] - The current page number for pagination (default: 0).
254   * @param {number} [itemsPerPage=9] - The number of items per page for pagination (default: 9).
255   * @returns {Promise<object[]>} A promise that resolves to an array of blog data objects.
256   * @throws {Error} If an error occurs while retrieving the data.
257   */
258  getAllBlogs: async function (
259    categories = [],
260    currentPage = 0,
261    itemsPerPage = 9,
262    guid = ""
263  ) {
264    try {
265      const response = await fetch(
266        `${this.apiBaseUrl}/umbraco/api/blogs/all?q=${categories.join(
267          ","
268        )}&cp=${currentPage}&ipp=${itemsPerPage}${guid ? "&guid=" + guid : ""}`,
269        {
270          headers: {
271            "Api-Key": this.apiKey,
272          },
273        }
274      );
275
276      if (!response.ok) {
277        throw new Error(
278          "An error occurred while retrieving the data. Please check the connection and try again."
279        );
280      }
281
282      const data = await response.json();
283      return data;
284    } catch (error) {
285      console.error("Error:", error);
286    }
287    return [];
288  },
289
290  /**
291   * Retrieve all categories of blogs from the API.
292   * @async
293   * @function getAllCategoriesOfBlogs
294   * @param {string} [guid=""] - An optional string of Guid to filter the blogs.
295   * @returns {Promise<string[]>} A promise that resolves to an array of category names.
296   * @throws {Error} If an error occurs while retrieving the data.
297   */
298  getAllCategoriesOfBlogs: async function (guid) {
299    try {
300      const response = await fetch(
301        `${this.apiBaseUrl}/umbraco/api/blogs/categories?${guid ? "guid=" + guid : ""}`,
302        {
303          headers: {
304            "Api-Key": this.apiKey,
305          },
306        }
307      );
308
309      if (!response.ok) {
310        throw new Error(
311          "An error occurred while retrieving the data. Please check the connection and try again."
312        );
313      }
314
315      const data = await response.json();
316      return data;
317    } catch (error) {
318      console.error("Error:", error);
319    }
320    return [];
321  },
322
323  /**
324   * Retrieve highlighted blogs from the API.
325   * @async
326   * @function getHighlightBlogs
327   * @returns {Promise<object[]>} A promise that resolves to an array of highlighted blog data objects.
328   * @throws {Error} If an error occurs while retrieving the data.
329   */
330  getHighlightBlogs: async function (guid = "") {
331    try {
332      const response = await fetch(
333        `${this.apiBaseUrl}/umbraco/api/blogs/highlights?${guid ? 'guid=' + guid : ''}`,
334        {
335          headers: {
336            "Api-Key": this.apiKey,
337          },
338        }
339      );
340
341      if (!response.ok) {
342        throw new Error(
343          "An error occurred while retrieving the data. Please check the connection and try again."
344        );
345      }
346
347      const data = await response.json();
348      return data;
349    } catch (error) {
350      console.error("Error:", error);
351    }
352    return [];
353  },
354};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.