@Yascer
@Yascer
@JPT
<div class="fb-like" data-href="https://www.facebook.com/yourpage" data-layout="button_count" data-action="like" data-size="small" data-share="false"></div>
<!-- تضمين مكتبة JavaScript الخاصة بـ Facebook -->
<script async defer src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2"></script>
يمكن وضع هذا الكود في أي مكان من صفحة الويب وسيتم عرض زر الإعجاب. يحتاج الزائرون إلى تسجيل الدخول إلى فيسبوك للتفاعل مع الزر.
يمكن تخصيص خصائص الزر من خلال تغيير القيم الموجودة في الـ attribute الخاص بالزر. مثلاً، data-share يحدد ما إذا كان يجب عرض زر المشاركة أم لا.
يتم تضمين مكتبة JavaScript من فيسبوك لتمكين التفاعل السلس بين المستخدم والزر. تأكد من عدم حجب هذا الرابط عند تصميم الصفحة.@Zizwar
@JPT
const { createClient } = require('@supabase/supabase-js')
const supabaseUrl = 'https://{YOUR_SUPABASE_URL}.supabase.co'
const supabaseKey = '{YOUR_SUPABASE_KEY}'
const supabase = createClient(supabaseUrl, supabaseKey)
const getVariableFromColumn = async () => {
const { data, error } = await supabase
.from('table_name')
.select('variable_name')
.eq('id', '123')
if (error) console.log('Error fetching data:', error.message)
else console.log('Data:', data)
}
getVariableFromColumn()
في هذا المثال، تم استخدام الدالة ".from" لتحديد جدول الذي سنجلب منه البيانات، والدالة ".select" لتحديد العمود والمتغير الذي نريد استخراجه، واستخدمنا "eq" لتحديد الشرط الذي يجب تحققه الصف المطلوب (وهو أن يكون id مساوي ل 123). وفي النهاية، تم استدعاء الدالة "getVariableFromColumn" لاستخراج البيانات وطباعتها إلى وحدة التحكم (console).@Zizwar
@JPT
typescript
import { HandlerContext } from "$fresh/server.ts";
import { getCookies } from "$std/http/cookie.ts";
import { emojify } from "emojify";
import { databaseLoader } from "@/communication/database.ts";
import { RoomChannel } from "@/communication/channel.ts";
import { badWordsCleanerLoader } from "@/helpers/bad_words.ts";
import { ApiSendMessage } from "@/communication/types.ts";
import { OpenAI } from "openai";
export async function handler(
req: Request,
_ctx: HandlerContext
): Promise<Response> {
const accessToken = getCookies(req.headers)["deploy_chat_token"];
if (!accessToken) {
return new Response("Not signed in", { status: 401 });
}
const database = await databaseLoader.getInstance();
const user = await database.getUserByAccessTokenOrThrow(accessToken);
const data = (await req.json()) as ApiSendMessage;
const channel = new RoomChannel(data.roomId);
const prooms = await database.getRoomPrompt(data.roomId);
const from = {
name: user.userName,
avatarUrl: user.avatarUrl,
};
if (data.kind === "isTyping") {
// Send `is typing...` indicator.
channel.sendIsTyping(from);
}
const badWordsCleaner = await badWordsCleanerLoader.getInstance();
const message = emojify(badWordsCleaner.clean(data.message));
channel.sendText({
message: message,
from,
createdAt: new Date().toISOString(),
});
await database.insertMessage({
text: message,
roomId: data.roomId,
userId: user.userId,
});
// Stream data from OpenAI and send to channel
if (message?.includes("@jpt")) {
const openAI = new OpenAI(Deno.env.get("KEY_OPEN_AI") ?? "");
const from = {
name: "@JPT",
avatarUrl: "https://jpt.ma/favicon.ico",
};
channel.sendIsTyping(from);
const userContent = message.replace("@jpt", "");
const SystemRoleContenet = prooms;
openAI.stream({
model: "davinci",
prompt: SystemRoleContenet + userContent + "\nJPT:",
temperature: 0.7,
stop: ["\n"],
}).on('data', (response) => {
const data = response?.choices?.[0]?.text.trim();
if (data) {
channel.sendText({
message: data,
from,
createdAt: new Date().toISOString(),
});
database.insertMessage({
text: data,
roomId: data.roomId,
userId: 12345666,
});
}
}).on('error', error => {
console.error(error);
});
}
channel.close();
return new Response("OK");
}
يرجى ملاحظة أن هذا الكود هو مجرد مثال، وقد تحتاج إلى تعديله ليتناسب مع احتياجات موقعك والمكتبات التي تستخدمها.@winoo
@winoo
@JPT
jsx
import { Auth, Button } from '@supabase/ui'
import { supabase } from '../lib/initSupabase' // استبدل هذا بملف التكوين الخاص بك
const auth = new Auth(supabase)
function RegisterButton() {
return (
<Button block onClick={() => auth.signup()}>Sign up</Button>
)
}
تحتاج إلى استبدال `../lib/initSupabase` بمسار ملف التكوين الخاص بتطبيق Supabase الخاص بك. وتذكر دائمًا استيراد `Auth`و `Button` من `@supabase/ui`.
يمكن استخدام `props` مثل `size` و `type` و `onClick` لتخصيص زر التسجيل عند الضرورة.
ملاحظة: يجب عليك تضمين تفاصيل Supabase الخاصة بك في ملف التكوين لتشغيل هذا الزر بشكل صحيح.@user1919
@JPT
jsx
import { useState, useEffect } from "preact/hooks";
import { IntlProvider, Text } from "preact-i18n";
- إضافة حالة للاختيار الحالي للغة، ودالة لتحديث اللغة:
jsx
const [locale, setLocale] = useState("en");
const changeLocale = (newLocale) => {
setLocale(newLocale);
setCookie("locale", newLocale); // Save language to cookies for future use
};
- تحميل ملفات الترجمة في useEffect (حيث data.locale يعود للاختيار السابق للزائر):
jsx
useEffect(() => {
const locale = getCookies().locale || data.locale || "en";
setLocale(locale);
import(`../locales/strings_${locale}.json`).then((strings) =>
setMessages(strings.default)
);
}, []);
- الآن يمكن استخدام المكونات والنصوص في الكود مع Text مثل هذا الشكل:
jsx
<Text id="welcome" />
- وفي ملف الترجمة (مثالًا `strings_en.json`)، يمكن وضع النصوص اللازمة مع التعليقات:
json
{
"welcome": "Welcome to my website",
"about": "About",
"contact": "Contact",
"message": "Send a message"
}
- يمكن استخدام مثل هذا الشكل لتغيير اللغة:
jsx
<button onClick={() => changeLocale("en")}>English</button>
<button onClick={() => changeLocale("ar")}>العربية</button>
وستتغير النصوص والمكونات وفقًا للغة التي يختارها الزائر.@2600ma
@JPT
db.createCollection("messages", {
validator: { $jsonSchema: {
bsonType: "object",
required: [ "created_at", "message" ],
properties: {
id: {
bsonType: "int"
},
created_at: {
bsonType: "date",
default: new Date(),
description: "timestamp with time zone default timezone('utc', now())"
},
message: {
bsonType: "string"
},
from: {
bsonType: "int",
description: "integer references users(id)"
},
room: {
bsonType: "int",
description: "integer references rooms(id)"
}
}
}},
validationAction: "error"
})
Note that MongoDB doesn't have support for auto-incremented IDs. Instead, we can use MongoDB's default `_id` field as a unique identifier for documents.
For the rooms_activity view, we won't be creating a view as in SQL databases. Instead, we'll be creating a MongoDB aggregation pipeline to get the required data. Here's the equivalent MongoDB code:
db.rooms.aggregate([
{
$lookup: {
from: "messages",
localField: "id",
foreignField: "room",
as: "messages"
}
},
{
$project: {
name: 1,
status: 1,
last_message_at: { $max: "$messages.created_at" }
}
},
{
$sort: { last_message_at: -1 }
}
])
This pipeline uses the `$lookup` stage to join the "messages" collection with the "rooms" collection, similar to a left join in SQL. Then, we use the `$project` stage to select the required fields from the "rooms" collection and compute the `last_message_at` field using `$max`. Finally, we use the `$sort` stage to sort the results in descending order of `last_message_at`.@2600ma
@JPT
jsx
import React from "react";
import { Helmet } from "react-helmet";
const MyWebsite = () => {
const title = "My Website"; // Page title
const description = "This is my awesome website"; // Page description
const ogImage = "https://example.com/og-image.jpg"; // Open Graph image for sharing on social media
const favicon = "https://example.com/favicon.ico"; // Site favicon
const author = "John Doe"; // Name of the author
return (
<>
<Helmet>
<title>{title}</title>
<meta name="description" content={description} />
{/* Open Graph meta tags */}
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={ogImage} />
<meta property="og:type" content="website" />
<link rel="shortcut icon" href={favicon} />
{/* Other meta tags */}
<meta name="author" content={author} />
<meta name="keywords" content="website, react, seo" />
{/* Add more meta tags if required */}
</Helmet>
{/* Rest of the website content */}
...
</>
);
};
export default MyWebsite;
Note that the `Helmet` component comes from the `react-helmet` library, which allows us to dynamically set meta tags in the `` section of the document. Also, make sure to replace the values of the variables with your own information to customize the SEO meta tags for your website.@2600ma
@JPT
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Website</title>
<!-- meta tags for SEO -->
<meta name="description" content="{{description}}">
<meta property="og:image" content="{{og_image}}">
<link rel="shortcut icon" href="{{favicon}}">
<!-- Preact library -->
<script type="module">
import { h, render, Component } from 'https://unpkg.com/preact@11.2.0?module';
</script>
<!-- additional scripts -->
<script src="/path/to/other/script.js"></script>
<!-- additional CSS -->
<link rel="stylesheet" href="/path/to/styles.css">
<!-- any other head elements -->
{{other_head_elements}}
</head>
<body>
<!-- your website content goes here -->
<!-- Preact app -->
<div id="app"></div>
<script type="module">
// your Preact app script goes here
</script>
<!-- any other scripts -->
<script src="/path/to/other/script2.js"></script>
<!-- any other footer elements -->
{{other_footer_elements}}
</body>
</html>
Here's a brief explanation of each variable and element:
- `{{description}}` - this variable can be replaced with a short description of your website that will appear as a snippet in search engine results.
- `{{og_image}}` - this variable can be replaced with the URL of an image that represents your website and will be displayed when users share your website on social media.
- `{{favicon}}` - this variable can be replaced with the URL of the icon that appears in the browser tab and bookmark bar.
- `{{other_head_elements}}` - this variable can be replaced with any additional elements you want to include in the head section of your website, such as additional meta tags or script references.
- `{{other_footer_elements}}` - this variable can be replaced with any additional elements you want to include in the body or footer section of your website, such as additional scripts or analytics tracking code.
Note that the content of these variables will depend on your specific website and should be customized accordingly.@cuteist
@JPT
JavaScript
console.log("this is a test");
This is a very simple example, and in real-world scenarios, you would create much more complex and functional code. However, this code demonstrates a basic understanding of how to use the `console.log()` function to output data to the console in JavaScript.@marocauto
@JPT
https://github.com/fluidicon.png
يمكن استخدام هذا الرابط لعرض الأيقونة على الموقع الخاص بك. يجب أن يتم تنسيق وتحجيم الصورة وفقًا لاحتياجات موقعك.@Zizwar
@JPT
@bidisignapor
@JPT
npm install next-translate language-tags
2. في ملف `next.config.js` ، أضف المكتبة `next-translate` وقم بتعيين اللغات المدعومة:
javascript
const withTranslations = require('next-translate');
module.exports = withTranslations({
// Define your supported languages here
i18n: {
locales: ['en', 'fr', 'ar'],
defaultLocale: 'en',
},
});
3. في صفحة الموقع الرئيسية أو في المكون الخاص بتغيير اللغة ، يجب استخدام مكتبة `language-tags` للتحقق من لغة المستخدم والتحقق من توفر ترجمة لهذه اللغة وتعيين اللغة الجديدة باستخدام `next-translate`:
javascript
import { useRouter } from 'next/router';
import LanguageTag from 'language-tags';
const LangSwitcher = () => {
// Use Next.js useRouter hook to get current locale
const router = useRouter();
// Get user language preference from browser
const browserLang = navigator.language || navigator.userLanguage;
// Create a language tag object from browser language
const langTag = new LanguageTag(browserLang);
// Check if the user-preferred language is supported
if (router.locales.includes(langTag.language)) {
// Set new locale using next-translate's `setLocale` method
router.push(router.asPath, router.asPath, { locale: langTag.language });
}
// ... render language switcher component
};
بعد هذه الخطوات ، يمكن للمستخدم التغيير بين اللغات وسيتم تخزين لغة المفضلة في مخزن الكوكيز لـ `next-translate` وسيتم استخدامها عندما يقوم المستخدم بزيارة الموقع في مرة أخرى.@JeanBIDI
@JPT
@JeanBIDI
@JPT
@bihay
@JPT
@bihay
@JPT
@bihay
@JPT
async insertUser(user: DatabaseUser & { accessToken: string }) {
const { error } = await this.#client.from("users").upsert(
[
{
id: user.userId,
username: user.userName,
avatar_url: user.avatarUrl,
access_token: user.accessToken,
},
],
{
returning: "minimal",
onConflict: {
columns: ["username", "avatar_url", "access_token"],
merge: ["username", "avatar_url", "access_token"],
},
}
);
if (error) {
throw new Error(error.message);
}
}
تم تحديد قيم "columns" و "merge" بشكل صحيح للمعلمة "onConflict"، والآن من المفترض أن تعمل الدالة بشكل صحيح.@bihay
@JPT
@bihisignapor-go
@JPT
@bihisignapor-go
@JPT
typescript
// Import dependencies
import { Context, Middleware } from 'https://deno.land/x/oak/mod.ts';
import { renderToString } from 'https://cdn.skypack.dev/preact-render-to-string';
import { h } from 'https://cdn.skypack.dev/preact';
// Google Analytics tracking ID
const googleAnalyticsId = 'UA-XXXXXXXXX-X';
// Google Analytics tracking script
const googleAnalyticsScript = `
<script async src="https://www.googletagmanager.com/gtag/js?id=${googleAnalyticsId}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${googleAnalyticsId}');
</script>
`;
// Middleware to inject Google Analytics tracking script
export const googleAnalyticsMiddleware: Middleware = async (ctx: Context, next: () => Promise<void>) => {
// Render the Preact Fresh application to a string
const appHtml = renderToString(h('div', {}, 'Hello, World!'));
// Inject the Google Analytics tracking script into the HTML string
const htmlWithAnalytics = `${appHtml}\n${googleAnalyticsScript}`;
// Send the modified HTML string as the response
ctx.response.body = htmlWithAnalytics;
// Call the next middleware
await next();
};
In this example, we're using the Oak framework for Deno to define a middleware function that injects the Google Analytics tracking script into the HTML response. The `googleAnalyticsMiddleware` function takes the `ctx` (context) and `next` (next middleware function) parameters.
Inside the middleware function, we first render the Preact Fresh application to a string using the `renderToString` function from the `preact-render-to-string` package. Then, we inject the Google Analytics tracking script into the HTML string with the `googleAnalyticsScript` variable.
Finally, we send the modified HTML string as the response and call the `next` middleware function to continue the request pipeline.
Note that you'll need to replace `UA-XXXXXXXXX-X` in the `googleAnalyticsId` variable with your actual Google Analytics tracking ID. Also, make sure to add this middleware function to your middleware stack in your application setup.@bihisignapor-go
@JPT
@bidisignapor-go
@JPT
javascript
const {google} = require('googleapis');
const keys = {"web":{"client_id":"23233-qf5ipfc.apps.googleusercontent.com","project_id":"wino-blogz","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"GOCSPX-232323"}};
// تفاصيل المدونة الخاصة بك على بلوجر
const BLOG_ID = '232323232323';
// أولاً نحتاج إلى الحصول على إذن للوصول إلى حساب جوجل الخاص بك من خلال مفاتيح API الخاصة بك.
async function authorize() {
const client = new google.auth.JWT(
keys.web.client_email, null,
keys.web.private_key, ['https://www.googleapis.com/auth/blogger']);
await client.authorize();
return client;
}
// إنشاء موضوع
async function createBlogPost(auth) {
const blogger = google.blogger({version: 'v3', auth});
const blogPost = {
title: 'عنوان المدونة الجديد',
content: 'هذا هو محتوى المدونة الجديد',
labels: ['تسميات اختيارية'],
blog: {
id: BLOG_ID
}
};
const res = await blogger.posts.insert(blogPost);
console.log(res.data);
}
// تشغيل نظام المصادقة وإنشاء الموضوع الجديد بعد ذلك
authorize().then(createBlogPost).catch(console.error);
يرجى استبدال `'عنوان المدونة الجديد'` و `'هذا هو محتوى المدونة الجديد'` و `['تسميات اختيارية']` في الكود السابق بمعلومات الموضوع الجديد الذي تريده.@settiricardo-go
@JPT
@marocautocomplete-go
@JPT
import { Handlers } from "$fresh/server.ts";
import { OpenAI } from "openai";
export const handler: Handlers = {
async POST(req, _ctx) {
try {
// const prompt = await req.text();
const data = (await req.json());
const openAI = new OpenAI(Deno.env.get("KEY_OPEN_AI") ?? "");
const chatCompletion = await openAI.createChatCompletion({
model: "gpt-3.5-turbo",
messages: [
{ "role": "system", "content": SystemRoleContenet },
{ "role": "user", "content": data.prompt},
],
});
console.log(chatCompletion);
const choices = chatCompletion?.choices;
const text = choices[0]?.message?.content ?? "gpt not respense";
return new Response(text, {
status: 200,
});
} catch (error) {
console.error("Error occurred while processing request: ", error);
return new Response("Something went wrong!", { status: 500 });
}
},
};
const SystemRoleContenet = "primpt system";
In this updated code, I have added a try-catch block around the `async POST` function code. This will catch any errors that may occur during the execution of the function. If an error occurs, it will log the error message to the console, and return a response with a status of 500 indicating a server error.@marocautocomplete-go
@JPT
javascript
fetch('/api/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ prompt: 'Hi there!' })
})
.then(response => response.text())
.then(text => console.log(text))
.catch(error => console.error(error));
In this example, we're sending a JSON object with a `prompt` property and value of `'Hi there!'`. We're also setting the content type header to `application/json`.
After sending the request, we're calling the `.text()` method on the response object to extract the response body.
Finally, we're logging the response body to the console. If an error occurs, we're logging it to the console as well.
Note that this is just an example, and you'll need to adjust the code to fit your specific use case.@2600ma-go
@JPT
// Code for frontend JavaScript in browser to record voice and send to backend
// Create an instance of a media recorder and initialize constraints for audio recording
const mediaRecorder = new MediaRecorder(stream);
const constraints = { audio: true };
// Start recording when user clicks the button
startButton.addEventListener('click', () => {
navigator.mediaDevices.getUserMedia(constraints)
.then(stream => {
mediaRecorder.start();
});
});
// Stop recording and send the recorded audio to the backend
stopButton.addEventListener('click', () => {
mediaRecorder.stop();
const audioBlob = new Blob(audioChunks); // Convert the audio chunks into a Blob object
const formData = new FormData(); // Create a new FormData object
formData.append('audio', audioBlob); // Add the audio Blob object to the FormData object
fetch('/api/recording', {
method: 'POST',
body: formData // Send the FormData object with the audio Blob to the backend
});
});
// Code for backend JavaScript in Deno to receive recording and send to OpenAI API Whisper
// Import dependencies
import { Application, Router } from 'https://deno.land/x/oak/mod.ts';
import { speak } from 'https://deno.land/x/whisper/mod.ts';
// Initialize the Oak application, create a router, and specify a route to receive the audio recording
const app = new Application();
const router = new Router();
router.post('/api/recording', async (ctx) => {
const audio = await ctx.request.body({ type: 'stream' }).value; // Get the audio stream from the request body
const text = await speak(audio, 'en-US'); // Use the Whisper library to convert the audio to text
console.log(text); // Log the text result to the console
});
// Start the application on port 8000
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });
In the frontend code, the `MediaRecorder` instance is created to record the audio stream. The `getUserMedia()` function prompts the user to allow access to their microphone. When the start button is clicked, the `start()` function begins recording the audio. When the stop button is clicked, the `stop()` function stops recording the audio and converts it into a `Blob` object. A `FormData` object is created, the `Blob` audio object is added to it, and the form data is sent to the backend using `fetch()`.
In the backend code, the `oak` and `whisper` dependencies are imported using the `import` statement. A new Oak application is created with a router specified to listen for incoming requests at the `/api/recording` route. When a request is received, it retrieves the audio stream from the request body and uses the `speak()` function from the `whisper` library to convert the audio to text. The resulting text is logged to the console. The application is then started on port 8000 using `await app.listen({ port: 8000 })`.@Zizwar-gi
@JPT
typescript
export class Database {
constructor() {
// No need to pass a client, create it inside the constructor
}
async searchVector(searchTerm: string): Promise<MessageView[]> {
const client = supabase.createClient(
Deno.env.get("SUPABASE_API_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!
);
const { data, error } = await client
.from("messages")
.select("*")
.textSearch("message", searchTerm) // Use textSearch method instead of raw SQL
if (error) {
console.error(error);
throw new Error(error.message);
} else {
console.log("result vector:", data);
return data;
}
}
// ...
}
In this updated code, the `searchVector` method creates the Supabase client inside the method and uses the `textSearch` method to perform the search query. This should resolve the error you were facing.@2600ma-go
@JPT
typescript
import { serve } from "https://deno.land/std/http/server.ts";
const server = serve({ port: 8000 });
console.log("Server started on port 8000");
// Create
async function handlePost(request: Request): Promise<Response> {
const cookie = request.headers.get("cookie");
const token = new URL(request.url).searchParams.get("token");
// Process the data and return JSON response
const data = { cookie, token };
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" },
});
}
// Read
async function handleGet(request: Request): Promise<Response> {
const endpoint = new URL(request.url).pathname; // Get the endpoint from the URL path
// Process the data and return JSON response
const data = { endpoint };
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" },
});
}
// Update
async function handlePut(request: Request): Promise<Response> {
// TODO: Implement your logic here
}
// Delete
async function handleDelete(request: Request): Promise<Response> {
// TODO: Implement your logic here
}
// Handle incoming requests
for await (const req of server) {
if (req.method === "POST") {
const response = await handlePost(req);
req.respond(response);
} else if (req.method === "GET") {
const response = await handleGet(req);
req.respond(response);
} else if (req.method === "PUT") {
const response = await handlePut(req);
req.respond(response);
} else if (req.method === "DELETE") {
const response = await handleDelete(req);
req.respond(response);
}
}
In this example, we have defined four basic CRUD operations - Create, Read, Update, and Delete. Currently, only the Create and Read operations are implemented (`handlePost` and `handleGet` functions respectively). You can add your logic for the Update and Delete operations in the corresponding functions (`handlePut` and `handleDelete`).
To start the server, run this script using the following command:
deno run --allow-net server.ts
This command allows network access (`--allow-net`) because we need to serve HTTP requests. It will start the server on `localhost:8000`. You can send HTTP requests to different endpoints (`localhost:8000/api/[endpoint]`) to test the CRUD operations.@2600ma-go
@JPT
javascript
import { serve } from "https://deno.land/std/http/server.ts";
const server = serve({ port: 8000 });
console.log("Server is running on http://localhost:8000/");
for await (const req of server) {
if (req.method === "GET") {
const url = new URL(req.url, `http://${req.headers.get("host")}`);
const endpoint = url.pathname.replace("/api/", "");
const cookie = req.headers.get("cookie");
let token;
if (url.searchParams.has("token")) {
token = url.searchParams.get("token");
}
// TODO: Perform CRUD operations based on the endpoint, cookie, and token
const response = {
data: "Your response data here",
};
req.respond({ body: JSON.stringify(response) });
}
}
Comments:
- We import the `serve` function from the `https://deno.land/std/http/server.ts` module to create an HTTP server.
- We create a server object and start it on port 8000.
- We listen for incoming requests using a `for await...of` loop.
- On each request, we check if the method is GET.
- We parse the URL and extract the endpoint from the pathname.
- We retrieve the `mojo_land` cookie from the request headers.
- We get the `token` value from the query parameters if it exists.
- ***TODO:*** You need to implement the CRUD operations based on the endpoint, cookie, and token. This will involve interacting with your database or data source.
- We construct a response object with the desired data.
- We respond to the request with a JSON stringified version of the response object.
Note: This code is a basic example to get you started with Deno's HTTP server capabilities. You need to implement the CRUD operations according to your requirements. Additionally, you may want to handle errors, validate input, and secure your endpoints with appropriate authentication and authorization mechanisms.@Zizwar-gi
@JPT
javascript
export default class Mojo {
async render(req, ctx, method) {
// قم بفصل وتجزئة المتغيرات والكائنات
const { gpt, db, filter } = ctx.state;
const url = new URL(req.url);
const query = (q) => url.searchParams.get(q);
// قم بفصل كود جلب البيانات بصيغة JSON
const body = method === "get" ? [] : (await req.json()) || [];
const json = (data, status = 200) => {
return new Response(JSON.stringify(data), {
status,
headers: { "Content-Type": "application/json" },
});
};
// قم بفصل كود إرجاع النص
const text = (text, status = 200) => {
return new Response(text, {
status,
});
};
// قم بإنشاء دالة لتسجيل الأحداث
const log = async ({ status, module = "mojo", action = "log", error: _error, log }) => {
// قم بتنفيذ كود تسجيل الأحداث هنا
};
// قم بتجزئة وإنشاء دالة لتنفيذ طلب البيانات من قاعدة البيانات
const getData = async (tableName, filters) => {
// قم بتنفيذ كود جلب البيانات من قاعدة البيانات هنا
};
// قم بفصل وتجزئة تحقق الصلاحية
const checkPermission = () => {
// قم بتنفيذ كود التحقق من الصلاحية هنا
};
// قم بفصل وتجزئة معالجة الفلترة
const applyFilters = async (db, tableName, filters) => {
// قم بتطبيق الفلاتر على قاعدة البيانات هنا
};
// قم بتجزئة وإنشاء دالة لتنفيذ الوظيفة الديناميكية
const executeDynamicFunction = async (codeFunction, context) => {
// قم بتنفيذ الوظيفة الديناميكية هنا
};
// قم بتجزئة وإنشاء دالة لتنفيذ طلب إنشاء البيانات
const createData = async (tableName, data) => {
// قم بتنفيذ طلب إنشاء البيانات هنا
};
// قم بتجزئة وإنشاء دالة لتنفيذ طلب تحديث البيانات
const updateData = async (tableName, data) => {
// قم بتنفيذ طلب تحديث البيانات هنا
};
// قم بتجزئة وإنشاء دالة لتنفيذ طلب حذف البيانات
const deleteData = async (tableName, id) => {
// قم بتنفيذ طلب حذف البيانات هنا
};
try {
// قم بتجزئة وتنفيذ طلب جلب البيانات ومعالجتها
const mojoData = await getData("mojos", {
endpoint: ctx.params.land || query("endpoint") || body?.endpoint || "intial",
});
// قم بتجزئة وتنفيذ طلب الاختيار والتصفية
const results = await applyFilters(db, mojoData.table, body?.filters);
// قم بفصل وتجزئة التحقق من الصلاحية
const hasPermission = checkPermission();
// قم بفصل العمليات المستندة على الوظيفة الديناميكية
if (mojoData.method === "function") {
// قم بتجزئة وتنفيذ الوظيفة الديناميكية
const result = await executeDynamicFunction(mojoData.function, ctx);
return result;
}
// قم بفصل العمليات المستندة على طلب إنشاء البيانات
if (mojoData.method === "create") {
// قم بتجزئة وتنفيذ طلب إنشاء البيانات
const result = await createData(mojoData.table, body?.insert);
return result;
}
// قم بفصل العمليات المستندة على طلب تحديث البيانات
if (mojoData.method === "update") {
// قم بتجزئة وتنفيذ طلب تحديث البيانات
const result = await updateData(mojoData.table, body?.update);
return result;
}
// قم بفصل العمليات المستندة على طلب حذف البيانات
if (mojoData.method === "delete") {
// قم بتجزئة وتنفيذ طلب حذف البيانات
const result = await deleteData(mojoData.table, query("id"));
return result;
}
// قم بتجزئة العمليات القائمة على تصفح البيانات
if (mojoData.method === "read") {
// قم بتنفيذ وتطبيق عملية التصفية
const result = await mojoFilter(null);
return result;
}
} catch (error) {
console.error("حدث خطأ أثناء معالجة الطلب: ", error);
// قم بتسجيل الخطأ هنا
return new Response("حدث خطأ، من فضلك حاول مرة أخرى!", { status: 500 });
}
return new Response("لا توجد خدمة مقدمة في هذا العنوان!", { status: 500 });
}
}
هذا هو الكود المجزأ والمعلق بشكل مناسب وقمت بتحويله إلى كلاس يسمى "Mojo" وتم تصديره كافتراضي. لاحظ@2600ma-go
@JPT
@marocautocomplete-go
@JPT
export default class Mojo {
async render(req, ctx, method) {
const { gpt, db, filter } = ctx.state;
const url = new URL(req.url);
const query = (q) => url.searchParams.get(q);
let body = [];
try {
body = method === "get" ? [] : (await req.json()) || [];
} catch (error) {
body = [];
}
const json = (data, status = 200) => {
return new Response(JSON.stringify(data), {
status,
headers: { "Content-Type": "application/json" },
});
};
const text = (text, status = 200) => {
return new Response(text, { status });
};
const log = async ({
status,
module = "mojo",
action = "log",
error: _error,
log,
}) => {
if (_error) action = "error";
try {
const { error } = await db.supabase.from("logs").insert({
status,
module,
action,
error: _error,
log,
});
if (error) {
throw JSON.stringify(error);
}
console.log("add log in db");
} catch (error) {
console.error("An error inserting data:", error.message);
throw error;
}
};
try {
let { data: mojoDATA, error } = await db.supabase
.from("mojos")
.select("*")
.eq("endpoint", ctx.params.land || query("endpoint") || body?.endpoint || "initial")
.single();
if (error) {
throw error;
}
const validColumns = (bodyData) => {
if (mojoDATA?.columns) {
const { columns } = mojoDATA;
if (columns === "all" || columns === "*") {
return bodyData;
} else {
const arrColumns = columns.split(",");
const validBody = Object.fromEntries(
Object.entries(bodyData).filter(([key]) =>
arrColumns.includes(key)
)
);
return validBody;
}
}
};
const checkPermission = () => {
if (!mojoDATA.method) return null;
const permission = mojoDATA?.permissions
? mojoDATA.permissions[mojoDATA.method]
: null;
if (!permission) return null;
const rolesArray = permission.split(",") || [];
const found = ctx.state?.user?.roles.some(
(roleObj) => rolesArray.includes(roleObj?.role.name)
);
return found;
};
const mojoFilter = async (mojoDB) => {
if (!checkPermission()) return json({ error: "not permission!" }, 403);
const id = query("id");
const uuid = query("uuid");
const limit = query("limit");
const page = query("page");
if (!mojoDB) {
mojoDB = await db.supabase
.from(mojoDATA.table)
.select(mojoDATA.select ?? mojoDATA.columns ?? "uuid");
}
if (id) {
mojoDB.eq("uuid", id || uuid);
} else if (uuid) {
mojoDB.eq("uuid", uuid);
}
if (mojoDATA.single) {
mojoDB.single();
}
if (limit) {
mojoDB.limit(limit);
}
if (page && mojoDATA?.pagination) {
mojoDB.range(page - 1, page + limit || 10);
}
console.log("----", body?.filters, mojoDATA?.filters);
if (body?.filters && mojoDATA?.filters) {
const validFilters = {};
for (const key in mojoDATA?.filters) {
if (Object.prototype.hasOwnProperty.call(mojoDATA?.filters, key)) {
const properties = mojoDATA?.filters[key].map((prop) => {
if (
body.filters[key] &&
body.filters[key][prop] !== undefined
) {
return [prop, body.filters[key][prop]];
} else {
console.log(
`Invalid key "${prop}" or missing value for filter "${key}"`
);
return null;
}
}).filter(Boolean);
validFilters[key] = properties;
}
}
const supportedFilters = [
"eq",
"gt",
"lt",
"gte",
"lte",
"like",
"ilike",
"is",
"in",
"neq",
"cs",
"cd",
];
for (const filter in validFilters) {
if (supportedFilters.includes(filter)) {
for (const [key, value] of validFilters[filter]) {
console.log("----", { filter }, { key, value });
switch (filter) {
case "eq":
mojoDB.eq(key, value);
break;
case "gt":
mojoDB.gt(key, value);
break;
case "lt":
mojoDB.lt(key, value);
break;
case "gte":
mojoDB.greaterThanOrEqual(key, value);
break;
case "lte":
mojoDB.lessThanOrEqual(key, value);
break;
case "like":
mojoDB.like(key, value);
break;
case "ilike":
mojoDB.ilike(key, value);
break;
case "is":
mojoDB.is(key, value);
break;
case "in":
mojoDB.in(key, value);
break;
case "neq":
mojoDB.neq(key, value);
break;
case "cs":
mojoDB.cs(key, value);
break;
case "cd":
mojoDB.cd(key, value);
break;
default:
console.log(`Unsupported filter: ${filter}`);
break;
}
}
} else {
console.log(`Unsupported filter: ${filter}`);
}
}
}
const { data = [], error } = await mojoDB;
if (error) {
await log({
status: mojoDATA.method,
error,
log: "Error In mOjO Land",
});
return json({ message: "Something went wrong!", error }, 500);
}
return json(data);
};
if (mojoDATA.method === "function") {
const codeFunction = mojoDATA?.function;
const content = SystemRoleContenet;
const dynamicFunction = new Function(
"mojo",
`
const { gpt, filter, body, db, endpoint } = mojo;
let { content } = mojo;
return (async () => {
//
${codeFunction}
//
})();
`
);
try {
return await dynamicFunction({
gpt,
body,
filter,
json,
text,
query,
content,
db,
log,
endpoint: ctx.params.land,
});
} catch (error) {
console.error("Error In Dynamic Function Mojo.Land: ", error);
await log({
status: "function",
error,
log: "Error In Dynamic Function Mojo.Land",
});
return json({ error: "Something went wrong!" }, 500);
}
}
if (mojoDATA.method === "create") {
const valideBodyInsert = validColumns(body?.insert);
if (!valideBodyInsert) return text("No data to insert in body.insert", 402);
let { data = [], error } = await db.supabase
.from(mojoDATA.table)
.insert(valideBodyInsert)
.select(mojoDATA.select || "uuid");
if (error) {
throw error;
}
return json(data);
}
if (mojoDATA.method === "rpc") {
let { data = [], error } = await db.supabase.rpc(mojoDATA.rpc, body);
if (error) {
throw error;
}
return json(data);
}
if (mojoDATA.method === "read") {
return await mojoFilter(null);
}
if (mojoDATA.method === "post") {
const mojoDB = db.supabase.from(mojoDATA.table).select(mojoDATA.select || mojoDATA.columns || "uuid");
return await mojoFilter(mojoDB);
}
if (mojoDATA.method === "update") {
console.log('body', body);
const valideBodyUpdate = validColumns(body?.update);
if (!valideBodyUpdate) return text("No data to update in body.insert", 402);
const mojoDB = db.supabase.from(mojoDATA.table).update(valideBodyUpdate).select(mojoDATA.select || mojoDATA.columns || "uuid");
return await mojoFilter(mojoDB);
}
if (mojoDATA.method === "delete") {
let { data = [], error } = await db.supabase
.from(mojoDATA.table)
.delete()
.eq("uuid", query("id"))
.select();
if (error) {
throw error;
}
return json(data);
}
if (mojoDATA.method === "data") {
return text(mojoDATA.data);
}
} catch (error) {
console.error("Error occurred while processing request: ", error);
await log({
status: "request",
error,
log: "Error occurred while processing request:",
});
return new Response("Something went wrong!", { status: 500 });
}
return new Response("No endpoint here!", { status: 403 });
}
}
@Zizwar-gi
@Zizwar-gi
@JPT
html
<form>
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="status">
Status
</label>
<input
class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
id="status"
type="text"
placeholder="Status"
>
</div>
<!-- اضف باقي الحقول هنا -->
<div class="flex items-center justify-between">
<button
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
type="button"
>
حفظ
</button>
</div>
</form>
أرجو أن يكون الكود مفهومًا ويحقق متطلباتك المذكورة. لقد استخدمت مكتبة CSS التي تعرف بـ "Tailwind" لتنسيق وتصميم الحقول والزر. يمكنك تخصيص المظهر عن طريق تعديل الفصول الخاصة بـ `class`.@JPT
html
<form class="m-4">
<!-- status -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="status">Status:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="status" name="status" type="text" placeholder="Status">
</div>
<!-- le_ar -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="le_ar">Le Ar:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="le_ar" name="le_ar" type="text" placeholder="Le Ar">
</div>
<!-- title_en -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="title_en">Title (EN):</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="title_en" name="title_en" type="text" placeholder="Title (EN)">
</div>
<!-- columns -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="columns">Columns:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="columns" name="columns" type="text" placeholder="Columns">
</div>
<!-- table -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="table">Table:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="table" name="table" type="text" placeholder="Table">
</div>
<!-- prefix -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="prefix">Prefix:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="prefix" name="prefix" type="text" placeholder="Prefix">
</div>
<!-- endpoint -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="endpoint">Endpoint:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="endpoint" name="endpoint" type="text" placeholder="Endpoint">
</div>
<!-- comment -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="comment">Comment:</label>
<textarea class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="comment" name="comment" rows="4" placeholder="Comment"></textarea>
</div>
<!-- data -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="data">Data:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="data" name="data" type="text" placeholder="Data">
</div>
<!-- permissions -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="permissions">Permissions:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="permissions" name="permissions" type="text" placeholder="Permissions">
</div>
<!-- custom_sql -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="custom_sql">Custom SQL:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="custom_sql" name="custom_sql" type="text" placeholder="Custom SQL">
</div>
<!-- function -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="function">Function:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="function" name="function" type="text" placeholder="Function">
</div>
<!-- role -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="role">Role:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="role" name="role" type="text" placeholder="Role">
</div>
<!-- method -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="method">Method:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="method" name="method" type="text" placeholder="Method">
</div>
<!-- select -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="select">Select:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="select" name="select" type="text" placeholder="Select">
</div>
<!-- rpc -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="rpc">RPC:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="rpc" name="rpc" type="text" placeholder="RPC">
</div>
<!-- single -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="single">Single:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="single" name="single" type="checkbox">
</div>
<!-- log -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="log">Log:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="log" name="log" type="checkbox">
</div>
<!-- filters -->
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2" for="filters">Filters:</label>
<input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="filters" name="filters" type="text" placeholder="Filters">
</div>
<!-- Submit button -->
<div class="flex items-center justify-center">
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit">
Submit
</button>
</div>
</form>
تم تصميم الـ form باستخدام إطار العمل Tailwind CSS وتم ترتيب الحقول وفقًا للأهمية كما ذكرت. يمكنك استخدام هذا الكود كنقطة انطلاق وتخصيصه وفقًا لمتطلباتك الخاصة في التصميم.
@Zizwar-gi
@JPT
import { h, Component } from 'preact';
import 'tailwindcss/tailwind.css';
class Form extends Component {
render() {
return (
<div class="p-4 space-y-4">
<input type="text" id="status" class="input-field" placeholder="Status" />
<input type="text" id="le_ar" class="input-field" placeholder="Le_ar" />
<input type="text" id="le_en" class="input-field" placeholder="Le_en" />
<input type="text" id="columns" class="input-field" placeholder="Columns" />
<input type="text" id="table" class="input-field" placeholder="Table" />
<input type="text" id="prefix" class="input-field" placeholder="Prefix" />
<input type="text" id="endpoint" class="input-field" placeholder="Endpoint" />
<textarea id="comment" class="input-field" placeholder="Comment"></textarea>
<textarea id="data" class="input-field" placeholder="Data"></textarea>
<input type="text" id="permissions" class="input-field" placeholder="Permissions" />
<input type="text" id="custom_sql" class="input-field" placeholder="Custom SQL" />
<input type="text" id="function" class="input-field" placeholder="Function" />
<input type="text" id="role" class="input-field" placeholder="Role" />
<input type="text" id="method" class="input-field" placeholder="Method" />
<input type="text" id="select" class="input-field" placeholder="Select" />
<input type="text" id="rpc" class="input-field" placeholder="RPC" />
<input type="checkbox" id="single" class="input-checkbox" />
<label for="single" class="ml-2">Single</label>
<input type="checkbox" id="log" class="input-checkbox" />
<label for="log" class="ml-2">Log</label>
<textarea id="filters" class="input-field" placeholder="Filters"></textarea>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
);
}
}
export default Form;
يرجى ملاحظة أن الشفرة تتضمن الحقول المعروضة في القاعدة данных التي قدمتها، وهي تولد استمارة بسيطة تتضمن مدخلات النص وزر الاختيار ومساحة النص ومربعات الاختيار. يمكنك تخصيص تنسيق الحقول وأنماط الألوان وفقًا لتطلعات التصميم الخاصة بك بواسطة تحرير فئات CSS المستخدمة في الأكواد.
أتمنى أن يكون هذا مفيداً لك!@alex.bryson29-go
@JPT
@alex.bryson29-go
@JPT
@alex.bryson29-go
@JPT
@Zizwar-gi
@JPT