قم بإنشاء وظيفة Google Cloud لإنشاء صور في تخزين Google Cloud

يوضح هذا المثال كيف يمكنك استخدام وظيفة Google Cloud لإنشاء صور رسم بياني مفتوحة من قالب Google Slides في Google Drive. يمكنك فتح أي صفحة على هذا الموقع والبحث عن og:image
علامة التعريف في الرأس لرؤية الصورة التي تم إنشاؤها مختلفة لكل صورة.
عندما يتم استدعاء وظيفة السحابة ، يتم توفير نص الإدخال في سلسلة الاستعلام وهذا يحل محل {{Title}}
العنصر النائب في القالب لإنشاء الصورة المخصصة. يتم تخزين الصورة التي تم إنشاؤها في تخزين Google Cloud ويتم إرجاع عنوان URL للملف العام.
إنشاء حساب خدمة
انتقل إلى console.cloud.google.com وإنشاء مشروع جديد من Google Cloud. أثناء اختيار المشروع ، انتقل إلى APIs & Services
> Credentials
> Create credentials
واختيار Service Account
.
امنح حساب الخدمة الخاص بك اسمًا وامنح Project > Owner
دور حساب الخدمة.
سيكون حساب الخدمة الخاص بك عنوان بريد إلكتروني مثل <project-id>-<service-account-name>@<project-id>.iam.gserviceaccount.com
.
ذات الصلة: استخدم حسابات الخدمة مع البرنامج النصي للتطبيقات
إنشاء مفتاح حساب الخدمة
في وحدة التحكم في Google Cloud ، انقر فوق عنوان البريد الإلكتروني لحساب الخدمة الذي قمت بإنشائه في خطوة المعاينة. انقر فوق مفاتيح> إضافة مفتاح> إنشاء مفتاح جديد. سيتم تنزيل ملف JSON على جهاز الكمبيوتر الخاص بك. تأكد من إضافة هذا الملف إلى .gitignore
الملف لأنه يحتوي على المفتاح الخاص ويجب ألا يلتزم بالمستودع.
يمكنك أيضًا تمرير بيانات اعتماد المصادقة إلى وظيفة السحابة عن طريق ضبط متغير البيئة GOOGLE_APPLICATION_CREDENTIALS
إلى مسار ملف JSON.
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/service-account.json"
تمكين واجهات برمجة تطبيقات Google Cloud
انتقل إلى APIS & Services> Library وتمكين Google Slides API
و Google Drive API
لمشروع السحابة الخاص بك.
إنشاء قالب شرائح Google
انتقل إلى شرائح Google وقم بإنشاء عرض تقديمي جديد يحتوي على شريحة واحدة. إضافة مربع نص يحتوي على النص {{TITLE}}
والتأكد من أن Resize shape to fit text
يتم التحقق من الخيار نظرًا لأن لدينا عنوانًا طويلًا أيضًا.
أضف بريد إلكتروني حساب الخدمة كمحرر إلى عرض Google Slides.
قم بإنشاء مجلد Google Drive
قم بإنشاء مجلد جديد في محرك Google الخاص بك وشاركه مع البريد الإلكتروني لحساب الخدمة. سيتم استخدام هذا المجلد لتخزين قوالب الشرائح التي يتم استخدامها لإنشاء صور الرسم البياني المفتوح.
قم بتدوين معرف المجلد وقالب الشرائح الذي تم إنشاؤه في الخطوة السابقة.
قم بإنشاء دلو تخزين سحابي
قم بالتبديل إلى تخزين Google Cloud وإنشاء دلو جديد لتخزين الصور التي تم إنشاؤها. يرجى ملاحظة أنه يجب تمكين الفواتير في مشروع Google Cloud الخاص بك لاستخدام هذه الميزة.
اكتب وظيفة Google Cloud
تهيئة مشروع جديد في القرص المحلي مع npm init
أمر وأضف الكود إلى ملف index.js. نقوم بإنشاء JWT الموقعة الخاصة بنا من المفتاح الخاص لحساب الخدمة ثم تبادل JWT للحصول على رمز الوصول لمصادقة واجهات برمجة تطبيقات Google.
const fetch = require('node-fetch');
const { google } = require('googleapis');
const { client_email, private_key } = require('./creds.json');
const { Storage } = require('@google-cloud/storage');
const { client_email, private_key } = require('./creds.json');
const jwtClient = new google.auth.JWT(client_email, null, private_key, [
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/presentations'
]);
const slides = google.slides({ version: 'v1', auth: jwtClient });
const drive = google.drive({ version: 'v3', auth: jwtClient });
const CLOUD_STORAGE_BUCKET = 'BUCKET_NAME_GOES_HERE';
const FOLDER_ID = 'DRIVE_FOLDER_ID_GOES_HERE';
const PRESENTATION_ID = 'PRESENTATION_ID_GOES_HERE';
const createOgImage = async (fileName, replaceText) => {
const { data: { id: presentationId } = {} } = await drive.files.copy({
fileId: PRESENTATION_ID,
fields: 'id',
requestBody: { name: fileName, parents: [FOLDER_ID] }
});
await slides.presentations.batchUpdate({
presentationId,
requestBody: {
requests: [
{
replaceAllText: {
replaceText,
containsText: { matchCase: false, text: '{{TITLE}}' }
}
}
]
}
});
const { data = {} } = await slides.presentations.get({
presentationId,
fields: 'slides/objectId'
});
const { data: { contentUrl } = {} } = await slides.presentations.pages.getThumbnail({
presentationId,
pageObjectId: data.slides[0].objectId
});
const response = await fetch(contentUrl);
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
await drive.files.delete({ fileId: presentationId });
return buffer;
};
const generateImagesAPI = async (req, res) => {
const storage = new Storage();
const bucket = storage.bucket(CLOUD_STORAGE_BUCKET);
const text = req.query.text;
const fileName = `${text.replace(/\s/g, '-').toLowerCase()}.png`;
const file = bucket.file(fileName);
const [fileExists] = await file.exists();
if (fileExists === false) {
const buffer = await createOgImage(fileName, text);
await file.save(buffer, {
resumable: false,
contentType: 'image/png',
public: true
});
await file.makePublic();
}
const fileLink = `${storage.apiEndpoint}/${CLOUD_STORAGE_BUCKET}/${fileName}`;
res.set('Cache-Control', 'public, max-age=86400, s-maxage=86400');
return res.redirect(fileLink);
};
module.exports = generateImagesAPI;
نشر وظيفة السحابة
إذا كنت تستخدم Firebase ، يمكنك نشر الوظيفة باستخدام firebase deploy --only functions
يأمر.
بعد نشر الوظيفة ، انتقل إلى وظيفة Google Cloud Console> Cloud وتحرير وظيفتك. توسيع Runtime, build, connections and security
قسم وتقليل تخصيص الذاكرة من 256MB
ل 128MB
. يمكنك أيضًا تقليل المهلة إلى وقت ما مثل 30s
لأنها ليست وظيفة كثيفة الموارد للغاية.