<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nui Somjin on Medium]]></title>
        <description><![CDATA[Stories by Nui Somjin on Medium]]></description>
        <link>https://medium.com/@naluinui?source=rss-2ec7fac6db8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*DS-2-WUK1WC27dER34pTmg.jpeg</url>
            <title>Stories by Nui Somjin on Medium</title>
            <link>https://medium.com/@naluinui?source=rss-2ec7fac6db8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 02:42:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@naluinui/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Perform vector similarity search with Firebase Data Connect and Genkit]]></title>
            <link>https://medium.com/@naluinui/perform-vector-similarity-search-with-firebase-data-connect-and-genkit-9def35c30d4b?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9def35c30d4b</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firebase-genkit]]></category>
            <category><![CDATA[genkit]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 18:54:29 GMT</pubDate>
            <atom:updated>2025-11-10T18:54:29.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgWDzv_-WdrESPMqJ5G8RQ.png" /></figure><p><a href="https://medium.com/firebase-developers/bring-relational-power-to-firebase-with-firebase-data-connect-e65e5c420ca8">Bring Relational Power to Firebase with Firebase Data Connect</a></p><p>In the previous article, we talked about Firebase Data Connect, Firebase’s first relational database service, powered by PostgresSQL on GCP Cloud. In this article, we’ll take a deeper look at another capability Firebase Data Connect has in mind for working with apps in the AI ​​Era.</p><h3>Understanding Vector Embeddings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zA9R3OKkc_MFfITF.png" /></figure><p><strong>A vector</strong> is a sequence of ordered numbers. The most common example we’re familiar with is geographical coordinates, which are a 2-dimensional vector composed of latitude and longitude, such as 37.751, -97.822. However, vectors are not limited to just 2 or 3 dimensions; they can have tens, hundreds, or even thousands of dimensions.</p><p><strong>Embeddings</strong> are the process of <strong>converting data into a vector</strong> (a sequence of ordered numbers) so that computers can understand and process it. Let’s learn from these examples.</p><p><strong>Example 1: Coffee ☕️</strong><br>Imagine representing coffee types using a <strong>3-dimensional vector</strong>, where each dimension represents the quantity of <strong>Coffee</strong>, <strong>Milk</strong>, and <strong>Sugar</strong>.</p><ul><li><strong>An americano</strong>, which has only coffee, no sugar, and no milk, might be represented as: <strong>(1.0, 0.0, 0.0)</strong>.</li><li><strong>A caramel macchiato</strong>, which has coffee, milk, and sugar, might be represented as: <strong>(1.0, 0.8, 0.5)</strong>.</li></ul><p>This method makes it much <strong>easier to analyze and compare</strong> different types of coffee.</p><p><strong>Example 2: Board Games 🎲<br></strong>In reality, board games might have many dimensions (e.g., fun level, difficulty, playtime, number of players).</p><p>To simplify, let’s look at just <strong>Fun Level</strong> and <strong>Difficulty</strong>. We can take each game and <strong>plot it on a graph</strong> where its position is the vector we just discussed. This is similar to the concepts we learned in high school, like <strong>Graph Theory</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pqrewAqHodc6GOJI.png" /></figure><p>Now we can use these values to calculate similarity or difference by measuring the distance between two points on the graph. Imagine a user wants a family game similar to Uno that is fun and not too difficult. We would then use the vector values to calculate which game is closest to Uno, and so on.</p><h3>Vector similarity search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ewku-QjjsbSqJ8tt.png" /></figure><p>Vector similarity search involves comparing embeddings to see which ones are most similar. To begin, we need to convert our data, whether it’s in text, image, audio, or file format, into vector embeddings and store them in a database that supports vector data.</p><p>When a user submits a query, we must also convert that text query into a vector embedding. This allows us to compare the query vector embedding with the vector embeddings stored in the database to find the most similar data, and then return the results to the user.</p><p>Reading up to this point, you might be wondering: <em>How do we convert data in our database into vector embeddings? Where can we store the data once it’s converted?</em> Well, Firebase Data Connect has you covered!</p><h3>Working with vector data in Firebase Data Connect</h3><p>So, getting back to the board game app, here are the four steps we’d take to implement the <strong>vector similarity search</strong> feature:</p><ol><li>Define the schema to accommodate vector data</li><li>Define the mutation to insert the vector data</li><li>Define the query for vector-enabled searching</li></ol><h4>1. Define the schema to accommodate vector data</h4><p>The advantage of PostgresSQL is that it can store vector data, which we can specify the data type Vectorin the schema file.</p><pre># ไฟล์ schema.gql<br>type Game @table {<br>  title: String!<br>  description: String!<br>  descriptionEmbedding: Vector<br>}</pre><h4>2. Define the mutation to insert the vector data</h4><p>Once the schema is defined, it’s time to write the data to the database</p><p><strong>2.1 Using an existing embedding model</strong></p><p>In cases where you already have an embedding model, for example, if you are using OpenAI’s text embedding models or a model developed in-house by your company. You can pre-convert the data into vector embeddings. Then, you simply write a mutation file to store those embeddings directly into the database, like the code example below:</p><pre>mutation CreateNewGame(<br>  $title: String!, <br>  $description: String!, <br>  $descriptionEmbedding: Vector!<br>) {<br>  game_insert(data: {<br>    title: $title,<br>    description: $description,<br>    descriptionEmbedding: $descriptionEmbedding<br>  })<br>}</pre><p><strong>2.2 Use Vertex AI vector embeddings from Firebase Data Connect</strong></p><p>If you don’t want the hassle of calling an external API to create the embeddings yourself, Firebase offers a wrapper function to simplify the process. We can use the special _embed command and specify the embedding model we need. This command automatically generates the embedding for us, leveraging <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings#supported-models">all embedding models from Vertex AI.</a></p><pre>mutation CreateNewGame(<br>  $title: String!, <br>  $description: String!, <br>  $descriptionEmbedding: Vector!<br>) {<br>  game_insert(data: {<br>    title: $title,<br>    description: $description,<br>    descriptionEmbedding_embed: {<br>      model: &quot;textembedding-gecko@003&quot;<br>      text: $description<br>    }<br>  })<br>}</pre><p>In the example, we embed the text description as embeddings with textembedding-gecko@003.</p><h4>3. Define the query for vector-enabled searching</h4><p>After collecting the vector data, let’s write a query to perform a vector similarity search.</p><pre>query SearchSimilarContent($query: String!, $limit: Int = 3)<br>@auth(level: PUBLIC) {<br>  games_descriptionEmbedding_similarity(<br>    compare_embed: {<br>      model: &quot;textembedding-gecko-multilingual@001&quot;<br>      text: $query<br>    }<br>    method: L2<br>    within: 2<br>    limit: $limit<br>  ) {<br>    ...DisplayGame<br>  }<br>}</pre><p>Firebase Data Connect creates a similarity function for every field that is a vector, and we can use this function to do a similarity search, like this:games_descriptionEmbedding_similarity</p><p>For converting the query that the user types into embeddings, we can call the compare_embed function. This tells Firebase Data Connect to convert the query string into its corresponding embedding. Here again, we can select models from Vertex AI. In this case, we use textembedding-gecko-multilingual@001 to ensure our search supports multiple languages (multilingual).</p><p>We can test the endpoint using VSCode Extensions (See how in <a href="https://medium.com/p/e65e5c420ca8">my previous article</a>). You’ll notice that we put in a very long search query written in Thai, yet the results returned from our database (which stores data in English) were surprisingly accurate (I promise it is!)✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VYLNrRuVnog6tnoW.png" /><figcaption>Thai text search results</figcaption></figure><p>This is incredibly comprehensive and can be adapted for tons of different use cases!</p><h3>Connect with Firebase Genkit to perform similarity search using keywords from an image</h3><p>In our demo, we added another feature that allows a user to submit an image, and the app will then search for similar games. This works by using Firebase Genkit to help extract keywords from the image. The resulting keywords are then used to search our database to find comparable games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lKs3HRBdf5yHM5pv.png" /><figcaption>Example of Similarity search using keywords from images in the demo</figcaption></figure><h3>Get to know Genkit</h3><p><a href="https://firebase.google.com/docs/genkit">Firebase Genkit</a></p><p><strong>Genkit</strong> is a tool that makes it easier for us to build AI apps. Its main advantage is that it can work with a variety of models, not just Google’s, and we can define data structures to make the answers we get from Generative AI more structured.</p><h3>Perform similarity search using keywords from images.</h3><p>As mentioned earlier, we will send the image to Gen AI to extract keywords (via Firebase Genkit) before searching our database for similar games.</p><p><strong>0. Install Firebase Genkit</strong></p><p>First of all, we need to install Firebase Genkit as per this document.</p><p><a href="https://firebase.google.com/docs/genkit/get-started">Get started | Genkit | Firebase</a></p><p>Then, use the command to add Genkit running on Cloud Functions for Firebase to our project.</p><pre>firebase init genkit</pre><p>After we have installed it, we will get a functions folder like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QMVWoprqHyr8JpXQ.png" /></figure><p>There will be sample source code for basic usage, including configGenkita flow example where we can see examples of writing and try testing basic functionality.</p><p><strong>Firebase Genkit</strong> also has <a href="https://firebase.google.com/docs/genkit/devtools">Developer Tools</a> for testing Flows and Models locally. We can install them according to this Document.</p><p><a href="https://firebase.google.com/docs/genkit/devtools">Firebase Genkit Developer Tools</a></p><p>Then use the command genkit startto start using Developer UI. Don&#39;t forget to download the necessary API key before running. export GOOGLE_GENAI_API_KEY=&lt;your API key&gt;If you choose to use Google AI, you can get the API key at <a href="https://aistudio.google.com/apikey">https://aistudio.google.com/apikey.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aTRS3dXQGwdYyt2l.png" /><figcaption>Genkit Developer Tools</figcaption></figure><ol><li><strong>Make a flow to extract keywords from images.</strong></li></ol><p>Now that we have the necessary tools installed, let’s start writing a flow to extract keywords from images. Creating a flow with Firebase Genkit</p><pre>export  const getKeywordFromPictureFlow = onFlow( <br>  { <br>    // Various configurations of the Flow<br>   }, <br>  async (input) =&gt; { <br>    // Flow operation steps such as <br>    // 1. Check if there is data <br>    // 2. Send data to GenAI to extract keywords <br>    // 3. Send the result back as a response<br>   } <br>);</pre><p>There are two components of Flow:</p><ul><li><strong>The configuration:</strong> include the flow name, input/output schema, and auth policy (Firebase Genkit works well with Firebase Authentication and can check access rights for each flow).</li></ul><pre>export const  getKeywordFromPictureFlow = onFlow( <br>  { <br>    name : &quot;getKeywordFromPictureFlow&quot; , <br>    inputSchema : z.string(), // Set to receive input as a string<br>    outputSchema: z.object({ // Set that the output will be in the format {keywords: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]}<br>      keywords: z.array(z.string()), <br>     }), <br>    // Allow only logged in users to use it to limit the use of GenAI which may cost 💸💸 (or other conditions as desired)<br>    authPolicy: firebaseAuth ((user) =&gt; {}), <br>    httpsOptions: { <br>      cors: true , <br>    }, <br>  }, <br>...</pre><ul><li><strong>The operation: </strong>like writing general functions to specify what actions are performed within the flow</li></ul><pre>... <br>  async(input) =&gt; { <br>    // Send input data to GenAI to extract keywords <br>    const llmResponse = await  generate({ <br>      // Specify the model you want to use, it can be claude3Sonnet, llama31, gpt4o, ollama <br>      model: gemini15Flash, // We choose gemini1.5Flash because it is multimodal that can work with images <br>      output: { <br>        format: &quot;json&quot;, // Say that we want structure data in the form of json <br>        schema: z.object({ // Define the structure of the desired output <br>          keywords: z.array(z.string()), <br>        }), <br>      }, <br>      // Define prompt <br>      prompt: [ <br>        // Throw input into media<br>         { media: { url: input } }, <br>        // Prompt that tells GenAI to extract keywords from the image <br>        // Try to reduce redundant words, suffixes to get keywords that are to the point <br>        // And brief it again that it should be sent back as an array<br>         { <br>          text : ` <br>            From the picture suggest 3 keywords or theme, avoid the word &#39;game&#39;, &#39;board&#39; or other decorative words. <br>            Return the keywords as an array list. eg [&#39;strategy&#39;, &#39;cooperative&#39;, &#39;worker placement&#39;] <br>          ` , <br>        }, <br>      ], <br>      config: { <br>        temperature : 1, <br>      }, <br>    }); <br>    return llmResponse.output() as { keywords: string[] }; <br>  } <br>);</pre><p>Using the command onFlowspecifies that this flow will be <a href="https://firebase.google.com/docs/genkit/flows#cloud_functions_for_firebase">deployed with Cloud Functions for Firebase</a> as a function within Cloud Functions.</p><p>Let’s test the flow in Developer tools before applying it to the UI. I sent an image URL of the MouseTrap game, our favorite game at home, as input and got the output in the specified object format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L0oY5VWssAquPbgR.png" /></figure><p><strong>2. Run in client</strong></p><p>To make local testing smooth, we first add the functions to our config and connect them to the Function emulators.</p><pre>/* lib/firebase.ts file */ <br><br>export  const firebaseApp = initializeApp ({ <br>  // your config from Firebase console<br> }) <br><br>const functions = getFunctions (firebaseApp) <br><br>if (import.meta.env.DEV) {<br>  connectFunctionsEmulator (functions, &#39;localhost&#39; , 5003 ) <br>  // ... other services used<br> } <br>export { functions }</pre><p>Then call the function httpsCallableas you would any other callable function from Cloud Functions for Firebase.</p><pre>export const extractKeywordsFromImage = async (<br>  input: string,<br>): Promise&lt;{ keywords: string[] }&gt; =&gt; {<br>  try {<br>    const getKeywords = httpsCallable(functions, &#39;getKeywordFromPictureFlow&#39;)<br>    const keywords = await getKeywords(input)<br>    return keywords.data as { keywords: string[] }<br>  } catch (error) {<br>    throw error<br>  }<br>}</pre><p>Assembled with UI logic</p><pre>const searchByImage = async (imageData?: string) =&gt; {<br>    if (!imageData) return<br>    isPending.value = true<br>    try {<br><br>      // Get keywords from image with Genkit<br>      const keywordsFromImage = (await extractKeywordsFromImage(imageData)) as {<br>        keywords: string[]<br>      }<br><br>      // Combine keywords to 1 long query string<br>      const imgQuery = keywordsFromImage.keywords.join(&#39; &#39;)<br><br>      // Use query string to perform similarity search with Firebase Data Connect<br>      const response = await searchSimilarContent({<br>        query: imgQuery,<br>        limit: 10,<br>      })<br><br>      // Use the results in the UI<br>      games.value = response.data<br>        .games_descriptionEmbedding_similarity as Game[]<br>    } catch (err) {<br>      console.error(&#39;searchByImage&#39;, error)<br>      if (err instanceof Error) error.value = err<br>    } finally {<br>      isPending.value = false<br>    }<br>  }</pre><p>That&#39;s it! We now have the similarity search feature using keywords from images 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpeS4Py2KZKr9goub4Se3A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McMNlMfRTrAgBmTT4zn7lA.jpeg" /></figure><p>This content is based on my talk, “Build better AI-driven Cloud SQL apps with Firebase Data Connect”</p><p>I used <strong>Firebase Data Connect</strong> and <strong>Genkit</strong> services to illustrate how easily you can add <strong>AI features</strong> to your apps. The examples highlight just one of many practical use cases for these powerful, convenient tools.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9def35c30d4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rebuilding NILA: Agile AI Agent with Firebase Genkit and GitHub MCP Server]]></title>
            <link>https://medium.com/@naluinui/rebuilding-nila-agile-ai-agent-with-firebase-genkit-and-github-mcp-server-266b8a668d51?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/266b8a668d51</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[genkit]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[firebase-genkit]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 20:55:58 GMT</pubDate>
            <atom:updated>2025-06-25T20:55:58.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wo2-uzlf2CQTPIs-KMg9FQ.png" /></figure><p>I can’t believe it’s almost 7 years since my friends and I first embarked (<em>during a hackathon</em>) to build “<strong>NILA: Naturally In Line Agile</strong>” — a chatbot designed to live within group chats, and support the needs of a software development team; <em>to discuss, decide, act… straight from chat</em>; <strong>to let teams collaborate naturally while maintaining their Agile management workflows</strong>. We were ever so excited when it won first prize at the LINE HACK hackathon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CO_0htqTYhpb9_NJBApffw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-Hr-DKc0mbF_fn9zyTx5A.jpeg" /><figcaption>Us looking very proud of ourselves and our team’s name “And yet it compiles” 🤣</figcaption></figure><p>Back then, we only had DialogFlow, which was cutting-edge for its time but often required a lot of “if-else” logic to manage conversational flows. Now, with the AI landscape completely evolved, it’s time to rebuild! and what better time than now, as part of the exciting <strong>#AISprint</strong>, to tackle on this journey?</p><p>This blog explores the possibility of Generative AI &amp; its tool-calling capability for NILA’s new chapter. I’ll be using Genkit and the GitHub MCP Server to achieve this.</p><h3>Genkit</h3><p>I chose <a href="https://genkit.dev/">Firebase Genkit</a> as our primary tool. It’s an open-source framework designed to help developers build applications with generative AI features. It provides a unified way to work with different AI models, with streamlined APIs for multimodal content, tool calling, and agentic workflows. It also comes with Genkit Developer Tools that lets you interactively work with models, flows, prompts, and other elements in your Genkit project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DdVBAhlAWvpKLvcAoX3HpA.gif" /><figcaption>Genkit Developer UI: for debugging &amp; interacting with your AI elements.</figcaption></figure><h3>The Architecture</h3><p>Let’s walk through the architecture of NILA. The journey starts in <strong>💬 Slack</strong>, where@NILA mention activates a <strong>Firebase Cloud Function</strong>. This function then sends the conversation context to our central <strong>🧠 AI Agent</strong>, which is orchestrated using <strong>Firebase Genkit</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaQarPM_UBOBzHCZl04kGQ.png" /><figcaption>NILA’s architecture</figcaption></figure><p><a href="https://genkit.dev/">Genkit</a> is the open-source framework that empowers our AI Agent. It provides the backbone for defining the agent’s behavior, integrating our Large Language Model (Gemini in this example) and enabling its advanced <strong>⚒️ </strong>tool-calling capabilities. This means our Genkit-powered agent will intelligently decide when to:</p><ul><li><strong>Use task writer agent </strong>to<strong> </strong>summarize information from the conversation and suggest a draft version of the issue.</li><li><strong>Interact with GitHub</strong> (via the MCP Server) to perform specific actions on GitHub: Create and update issues, track status, etc.</li><li><strong>Generate direct responses:</strong> Beyond tool calls, the AI Agent can also provide conversational responses, ask clarifying questions, or confirm actions.</li></ul><p>Once done, it returns the outcome directly to Slack. This could be the drafted issue for user confirmation, a confirmation message that an issue has been created (along with a link to the new issue), or simply a helpful answer to a query.</p><h3>The Implementation</h3><p>Follow along to the repo below for the code and detailed instructions to get it up and running</p><p><a href="https://github.com/naluinui/nila-ai">GitHub - naluinui/nila-ai: Slackbot to help streamline your Agile process. Powered by Firebase Genkit and GitHub MCP Server</a></p><p>Now let’s understand how each bit of the code works.</p><h4><strong>1. Slack Webhook (The entry point 💬)</strong></h4><p>Everything starts in src/index.ts, where we set up Firebase Cloud Functions for the Slack webhook. It’s using Bolt Slack framework for the Event API.</p><p>The main Slack logic is in <a href="https://github.com/naluinui/nila-ai/blob/main/functions/src/slack/index.ts">slack/index.ts</a> where it receives the app_mention event. When your bot is mentioned, this function does a few critical things</p><p><strong>1. Provides user feedback</strong>: It immediately sends a “typing…” message so. the user knows their request is being processed</p><pre>// thinking...<br>const botMessage = await say({<br>  thread_ts: ts,<br>  text: &quot;typing...&quot;,<br>});</pre><p><strong>2.</strong> <strong>Gets context</strong>: It calls <a href="https://github.com/naluinui/nila-ai/blob/main/functions/src/slack/util.ts">getThread()</a> to fetch the entire conversation history from the Slack thread. This gives the AI the full context of the discussion, not just the single message.</p><pre>// Getting context messages from the thread<br>const botUserId = await getBotId(); // get the bot user id<br>const messages = await getThread(channel, ts, botUserId);</pre><p><strong>3. Calls the agent</strong>: It invokes the <a href="https://github.com/naluinui/nila-ai/blob/main/functions/src/ai/agent/index.ts">chatAgent</a> with the message history and additional context, like a link to the thread and the default GitHub repository.</p><pre>const answer = await chatAgent(<br>  // Input: messages from the thread<br>  messages,<br>  // Context: Passing extra context to agent. Read more: https://genkit.dev/docs/context/<br>  {<br>    context: {<br>      // link to thread so that agent can refer to it when needed (for task description)<br>      link_to_thread: await getLinkToThread(channel, ts),<br>      // default github owner and repo (so that agent can use it for all operations, but can be overridden by user)<br>      github_owner: &quot;[your_github_account_or_organization]&quot;,<br>      github_repo: &quot;[your_github_repo]&quot;,<br>    },<br>  }<br>);<br><br>console.info(&quot;[AI] ✨ Answer:&quot;, answer);<br><br>await client.chat.update({<br>  channel,<br>  ts: botMessage.ts as string,<br>  text: answer || &quot;Sorry, I don&#39;t know the answer.&quot;,<br>});</pre><h4>2. AI Agent (The brain 🧠)</h4><p>The core intelligence of NILA resides in the ai/directory. This is where we define the agent’s behavior, its tools, and how it interacts with the language model. Let’s break down its structure:</p><pre>ai/<br>├── index.ts # Initializes Genkit and plugins<br>└── agent/<br>  ├── index.ts # Defines the main chat agent flow<br>  ├── type.ts # Defines data types (schemas)<br>  └── tools/<br>    ├── custom.ts # Defines custom agent tools<br>    └── github-mcp.ts # Configures the GitHub MCP tool client</pre><p>This is the starting point for our AI configuration. In <a href="https://github.com/naluinui/nila-ai/blob/main/functions/src/ai/index.ts">ai/index.ts</a>, we initialize Genkit with the necessary plugins. This tells our agent what model we want to use, and what capabilities are available. I use Gemini 2.5 Flash in GoogleAI for this example. But as mentioned previously, with Genkit, you can use <a href="https://www.npmjs.com/search?q=genkitx">other supported models</a> of your choice.</p><pre>export const ai = genkit({<br>  plugins: [googleAI({ apiKey: process.env.GOOGLEAI_API_KEY })], // TODO: add mcp client here in the next step<br>  model: googleAI.model(&quot;gemini-2.5-flash-preview-04-17&quot;),<br>});</pre><p>The main Chat flow is located in <a href="https://github.com/naluinui/nila-ai/blob/main/functions/src/ai/agent/index.ts">ai/agent/index.ts</a> where I used ai.defineFlow to create the chatAgent. Here we provided the DEFAULT_SYSTEM_INSTRUCTION. This prompt is the agent&#39;s constitution. It defines its personality, capabilities, and constraints.</p><p>The flow takes the messages and context from Slack, combines them with the system prompt, and calls the AI model, making a specific set of tools available.</p><pre>const DEFAULT_SYSTEM_INSTRUCTION = `<br>  You are a helpful AI assistant specialized in supporting scrum teams by managing tasks and facilitating the scrum process. Your primary goal is to accurately track and manage tasks within GitHub, while ensuring user satisfaction and confirmation at each step.<br>`;<br>// TODO: add more prompt<br><br>export const chatAgent = ai.defineFlow(<br>  {<br>    name: &quot;chatAgent&quot;,<br>    inputSchema: messagesSchema,<br>    outputSchema: z.string(),<br>  },<br>  async (messages, { context }) =&gt; {<br>    const systemInstruction = DEFAULT_SYSTEM_INSTRUCTION +<br>      (context<br>        ? ` where github owner is ${context?.github_owner} and repo is ${context?.github_repo} and link to thread is ${context?.link_to_thread}`<br>        : &quot;&quot;);<br>    try {<br>      const llmResponse = await ai.generate({<br>        system: systemInstruction,<br>        messages: messages,<br>        context: context,<br>        model: googleAI.model(&quot;gemini-2.5-flash-preview-04-17&quot;),<br>        tools: [<br>          // TODO: provide tools<br>        ],<br>        config: {<br>          temperature: 1, // Set the creativity/variation of the response<br>        },<br>      });<br><br>      return llmResponse.text;<br><br>    } catch (error) {<br>      console.error(&quot;[AI] 🔴 error:&quot;, error);<br>      return `I encountered an error while processing your request. ${<br>        error instanceof Error ? error.message : &quot;Unknown error&quot;<br>      }. Please try again later.`;<br>    }<br>  }<br>);</pre><h4>3. Tool Callings (The actions ⚒️)</h4><p>This is where the magic happens. Instead of just talking, the agent can <em>do</em> things. To provide tools in Genkit, you can 1) use ai.defineTool to create your own custom tools, or 2) use MCP Client to connect to the other tools via the MCP Server.</p><p>In this project, we’ve got both! Let’s see how we define and use them</p><p><strong>Custom tools</strong></p><p>In <a href="https://github.com/naluinui/nila-ai/blob/main/functions/src/ai/agent/tools/custom.ts">ai/agent/tools/custom.ts</a>, we define a taskWriterAgent. This is a simple AI prompt that&#39;s exposed as a tool. The main chatAgent can call this tool when it needs to draft a GitHub issue, fulfilling the requirement from its system prompt</p><pre>// tools/custom.ts<br>export const taskWriterAgent = ai.prompt(&quot;taskWriter&quot;);</pre><pre># prompts/taskwriter.prompt<br>---<br>model: googleai/gemini-2.0-flash<br>description: This agent helps users draft the task.<br>config:<br>  temperature: 0.8<br><br>---<br>[SYSTEM NOTE: Internal Task Formulation Agent. Input: &#39;Studied context&#39; from primary agent regarding user&#39;s intent to create a task. Output: Structured task data. No user interaction.]<br><br>Your function is to process the provided &#39;studied context&#39; and generate a structured task description. Analyze the context through a **Product Owner lens**, focusing on user need, value, and the &quot;What/Why.&quot;<br><br>**Objective:** Formulate data to populate the following task fields, extracting or inferring information *solely* from the provided context. Do your best to make fields comprehensive.</pre><p><strong>GitHub MCP server</strong></p><p>In <a href="https://github.com/naluinui/nila-ai/blob/main/functions/src/ai/agent/tools/github-mcp.ts">ai/agent/tools/github-mcp.ts</a>, we connect to the GitHub MCP server via the mcpClient function. You can connect to any MCP server via various methods, including npx, sse, or remote MCP Server. GitHub Remote MCP Server requires authentication in the request header, which you can configure using StreamableHTTPClientTransport with Genkit’s transport</p><pre>// ai/agent/tools/github-mcp.ts<br>import { mcpClient } from &quot;genkitx-mcp&quot;;<br>import { StreamableHTTPClientTransport } from &quot;@modelcontextprotocol/sdk/client/streamableHttp.js&quot;;<br><br>export const githubClient = mcpClient({<br>  name: &quot;github&quot;,<br>  version: &quot;1.12.0&quot;,<br>  transport: new StreamableHTTPClientTransport(<br>    new URL(&quot;https://api.githubcopilot.com/mcp/&quot;),<br>    {<br>      requestInit: {<br>        headers: {<br>          authorization: `Bearer ${<br>            process.env.GITHUB_PERSONAL_ACCESS_TOKEN || &quot;&quot;<br>          }`,<br>        },<br>      },<br>    }<br>  ),<br>});</pre><p>We also need to make sure we include this in the AI Configuration step too!</p><pre>// ai/index.ts<br>import { githubClient } from &quot;./agent/tools/github-mcp&quot;;<br><br>export const ai = genkit({<br>  plugins: [googleAI({ apiKey: process.env.GOOGLEAI_API_KEY }), githubClient],<br>  model: googleAI.model(&quot;gemini-2.5-flash-preview-04-17&quot;),<br>});</pre><p>After this step, if we look into the Developer UI (by running pnpm dev), we should see that there are a bunch of tools (56 to be precise!) available for us to use without us having to write any complex API wrappers.</p><p>Next, we’ll also need to tell our chatAgent about these handy tools it can use. By sending the list of tools and providing a clear instruction in the DEFAULT_SYSTEM_INSTRUCTION our agent will figure out the right tool at the right time.</p><pre>import { taskWriterAgent } from &quot;./tools/custom&quot;;<br><br>const DEFAULT_SYSTEM_INSTRUCTION = `<br>  You are a helpful AI assistant specialized in supporting scrum teams by managing tasks and facilitating the scrum process. Your primary goal is to accurately track and manage tasks within GitHub, while ensuring user satisfaction and confirmation at each step.<br>  <br>  Here&#39;s how you should operate:<br><br>  **1. Contextual Understanding:**<br>  * **Discussion Analysis:** Always refer to the {{input.messages}} to fully understand the user&#39;s current request or ongoing discussion, especially for nuanced or multi-turn interactions.<br>  * **GitHub Repository Context:** Pay close attention to whether the user provides a **GitHub repository owner** (e.g., &quot;my-org&quot;, &quot;username&quot;) and a **repository name** (e.g., &quot;my-project&quot;, &quot;scrum-repo&quot;). If provided, **store and utilize this information as the default context for all subsequent GitHub operations** until explicitly changed by the user. If this information is not provided, you may need to ask for it when a GitHub operation requires it.<br><br>  **2. Task Creation Workflow:**<br>  * **Drafting:** When the user requests to create a new task, **do not create it immediately.** First, use the \`taskWriterAgent\` tool to generate a draft of the task details (e.g., title, description, assignee, labels). Present this draft to the user and explicitly ask for their confirmation.<br>  * **Revision:** If the user is not satisfied with the drafted task, utilize the \`taskWriterAgent\` tool again to revise the task based on their feedback. Continue this revision and confirmation loop until the user explicitly approves the task draft.<br>  * **Final Creation:** Once the user explicitly confirms satisfaction with the drafted task, use the \`github/create_issue\` tool to create the task in GitHub. **Ensure that \`link to thread\` is added as relevant discussion and &quot;&gt; created by NILA AI ✨&quot; is appended to the task&#39;s description.**<br><br>  **3. Task Management Actions:**<br>  * **Updating a Task:** If the user asks to update an existing task, use the \`github/update_issue\` tool, ensuring you have the necessary \`issue_id\`.<br>  * **Retrieving a Specific Task:** If the user asks to get details of a specific task, use the \`github/get_issue\` tool, ensuring you have the necessary \`issue_id\`.<br>  * **Listing Tasks/Getting Status (Contextual):** If the user asks about the &quot;status of a task&quot; or similar without providing a specific \`issue_id\`, use the \`github/list_issues\` tool to provide relevant context and help them locate the desired task.<br><br>  **4. Error Handling &amp; Scope:**<br>  * **Out of Scope:** If a user&#39;s request falls outside your defined capabilities (task management within GitHub via the specified tools), respond politely with phrases such as: &quot;I&#39;m not equipped to handle that request,&quot; &quot;I can only assist with GitHub task management,&quot; or &quot;I can&#39;t help with that particular request.&quot;<br>  * **Tool Execution Errors:** If an error occurs when attempting to use a tool (e.g., \`github/create_issue\`), inform the user clearly: &quot;I encountered an error while trying to process your request. Please try again later, or check the details you provided.&quot; or &quot;It seems there was an issue completing that action.&quot;<br><br>  **Key Principles:**<br>  * **Confirmation-Driven:** Prioritize user confirmation for task creation.<br>  * **Clarity:** Ensure your responses are clear and directly address the user&#39;s intent.<br>  * **Helpful:** Aim to streamline the scrum task management process.<br>  * **Context-Aware:** Proactively use provided GitHub owner/repo information for all relevant operations.<br>`;<br><br>export const chatAgent = ai.defineFlow(<br>  {<br>    name: &quot;chatAgent&quot;,<br>    inputSchema: messagesSchema,<br>    outputSchema: z.string(),<br>  },<br>  async (messages, { context }) =&gt; {<br>    ...<br>    try {<br>      const llmResponse = await ai.generate({<br>        ...<br>        tools: [<br>          taskWriterAgent,<br>          &quot;github/create_issue&quot;,<br>          &quot;github/update_issue&quot;,<br>          &quot;github/get_issue&quot;,<br>          &quot;github/list_issues&quot;,<br>        ],<br>        ...<br>      });<br><br>      return llmResponse.text;<br><br>    } catch (error) {<br>      ...<br>    }<br>  }<br>);</pre><p>And with that, we should have a *smarter* version of NILA, who can help summarize, create, and track the issue… straight from your chat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*XvVOz6Div42_H4gfRS5s-Q.png" /><figcaption>NILA in action</figcaption></figure><p>It’s been an exciting journey rebuilding NILA with Firebase Genkit and the GitHub MCP Server. We’ve explored how modern AI, especially with its powerful tool-calling capabilities, can streamline Agile workflows. NILA, in its new form, is more than just a chatbot that acts with pre-defined, specific intents (like how it was with DialogFlow). This new version of NILA leverages generative AI to <strong>understand natural language, intelligently respond, and proactively act</strong> based on context.</p><p>You’ve now seen the architecture, the implementation, and the core components that bring this smarter NILA to life. We’ve open-sourced NILA’s code, so you’re not just reading about it. you can <strong>build it, experiment with it, and make it your own</strong>.</p><p>Here are some ideas you can take NILA further:</p><ul><li><strong>Expand to other platforms:</strong> NILA currently lives in Slack, but its brain part (AI Agent) is designed to be reusable. You can integrate it with other communication platforms like LINE, or WhatsApp to support your team’s preferred channel.</li><li><strong>Integrate more tools:</strong> The GitHub MCP Server is just one example. We could connect to more tools that suit your team.</li><li><strong>Refine its intelligence:</strong> Experiment with different AI models or fine-tune NILA’s system instructions to better suit your team’s unique communication style and workflow. How can you make NILA anticipate needs or offer proactive suggestions?</li></ul><p>Ready to dive in? You can find all the code and detailed instructions in the repository. I can’t wait to see what you build!</p><p><a href="https://github.com/naluinui/nila-ai">GitHub - naluinui/nila-ai: Slackbot to help streamline your Agile process. Powered by Firebase Genkit and GitHub MCP Server</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=266b8a668d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ทำ Vector similarity search กับ Firebase Data Connect และ Firebase Genkit]]></title>
            <link>https://medium.com/firebasethailand/%E0%B8%97%E0%B8%B3-vector-similarity-search-%E0%B8%81%E0%B8%B1%E0%B8%9A-firebase-data-connect-%E0%B9%81%E0%B8%A5%E0%B8%B0-firebase-genkit-9d3364e81cea?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d3364e81cea</guid>
            <category><![CDATA[firebase-genkit]]></category>
            <category><![CDATA[firebase-database]]></category>
            <category><![CDATA[genkit]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 15:33:50 GMT</pubDate>
            <atom:updated>2024-12-03T15:33:50.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgWDzv_-WdrESPMqJ5G8RQ.png" /></figure><p><a href="https://medium.com/firebasethailand/firebase-data-connect-%E0%B8%9A%E0%B8%A3%E0%B8%B4%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%97%E0%B8%B3%E0%B9%83%E0%B8%AB%E0%B9%89-firebase-%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B8%81%E0%B8%B1%E0%B8%9A-postgressql-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B9%86-43a3b0ff6141">Firebase Data Connect บริการที่ทำให้ Firebase เชื่อมต่อกับ PostgresSQL ได้แบบง่ายๆ</a></p><p>จากบทความที่แล้ว เราได้พูดถึง Firebase Data Connect บริการที่รองรับ Relational Database ตัวแรกของ Firebase โดยเบื้องหลังคือ PostgresSQL บน GCP Cloud บทความนี้เราจะมาเจาะลึกในความสามารถอีกอย่างที่ Firebase Data Connect คิดมาให้แล้ว สำหรับการทำงานกับแอปในยุค AI Era</p><h3>เข้าใจ Vector embeddings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q_tjFQnHLQG390kIggUt0Q.png" /></figure><p><strong>Vector</strong> คือ ชุดตัวเลขที่เรียงลำดับกัน ที่เราน่าจะรู้จักกันดีคือ พิกัดทางภูมิศาสตร์ ซึ่งจะเป็นเวกเตอร์ 2 มิติ ที่ประกอบด้วย lattitude, longitude เช่น 37.751 , -97.822 แต่เวกเตอร์ไม่จำกัดแค่ 2 หรือ 3 มิติ อาจมีหลายสิบ หลายร้อย หรือหลายพันมิติก็ได้</p><p><strong>Embeddings</strong> คือ การแปลงข้อมูลให้เป็นเวกเตอร์ เพื่อให้คอมพิวเตอร์สามารถเข้าใจและประมวลผลได้ เช่น การแทนกาแฟด้วยเวกเตอร์ 3 มิติ โดยแต่ละมิติแทนปริมาณของกาแฟ นม และน้ำตาล ซึ่งอเมริกาโน่ อาจจะมีแค่กาแฟ ไม่มีน้ำตาลและนม 1.0,0.0,0.0 แต่คาราเมลมัคคิอาโต้ มีทั้ง กาแฟ นม น้ำตาล 1.0,0.8,0.5อย่างนี้ก็จะทำให้เราวิเคราะห์และเปรียบเทียบประเภทของกาแฟต่างๆ ได้ง่ายขึ้นนั่นเอง</p><p>หรืออย่างบอร์ดเกม จริงๆอาจจะมีได้หลายมิติ ไม่ว่าจะเป็น ความสนุก ความยาก ระยะเวลาการเล่น จำนวนผู้เล่น เพื่อทำให้เห็นภาพง่ายขึ้นเราจะดู ความสนุก และ ความยาก โดยเราจะนำแต่ละเกมมา plot เป็นกราฟ ซึ่งตำแหน่งของมันก็คือ vector ที่เราเรียกกันนั่นแหละ เหมือนที่เราเรียนเรื่องทฤษฏีกราฟตอนม.ปลายเลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4qTspb-Wj12CStDW5nQEQ.png" /></figure><p>ทีนี้เราก็สามารถเอาค่านี้ มาคำนวณว่าเหมือนหรือต่างด้วยคำนวณระยะห่างระหว่างจุดสองจุดบนกราฟ ลองจินตนาการว่า user อยากอยากได้เกมครอบครัวคล้ายๆกับ uno ที่สนุก เล่นไม่ยากมาก ทีนี้เราก็จะเอาค่า vector คำนวณว่าอันไหนใกล้เคียง uno สุด เป็นต้น</p><h3>Vector similarity search</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbvNV_xK9irARHUEdBtcEQ.png" /></figure><p>การทำ Vector similarity search คือการนำ embeddings มาเทียบกันว่าอันไหนมีความใกล้เคียงกันมากที่สุด โดยเริ่มต้นเลยเราต้องนำข้อมูลของเรา ไม่ว่าจะอยู่ในรูปแบบ text, image, audio, file ไปแปลงเป็น vector embeddings ก่อน แล้วเก็บไว้ใน database ที่รองรับการเก็บข้อมูลในรูปแบบ vector</p><p>พอ user ส่ง query เข้ามา เราก็จะต้องเอา query ที่เป็น text แปลงเป็น vector embeddings เพื่อที่เราจะสามารถนำ vector embeddings นั้นไปเปรียบเทียบกับ vector embeddings ที่เก็บเอาไว้ใน database เพื่อหาข้อมูลที่ใกล้เคียงกัน แล้วโยนผลลัพธ์ กลับออกไปให้ user</p><p>อ่านมาถึงตรงนี้ ทุกคนอาจจะสงสัยว่า<em> แล้วเราจะแปลงข้อมูลที่อยู่ใน Database ของเราให้เป็น vector embeddings ได้ยังไง? พอแปลงแล้วเราจะเอาข้อมูลไปเก็บไว้ที่ไหนได้บ้าง? </em>บอกเลย<em> </em>Firebase Data Connect คิดมาให้แล้ว~</p><h3>ทำงานกับข้อมูลแบบ vector ใน Firebase Data Connect</h3><p>กลับไปที่แอปบอร์ดเกมของเรา สมมุติว่าเราจะเพิ่มฟีเจอร์สำหรับค้นหาแบบ vector similarity search กระบวนท่าจะถูกแบ่งเป็น 4 ขั้นตอน ดังนี้</p><ol><li>เพิ่ม schema ที่ทำให้รองรับการเก็บข้อมูลแบบ Vector</li><li>เพิ่ม mutation ในการเขียนข้อมูลที่เป็น Vector</li><li>เขียน query ให้รองรับการค้นหาด้วย Vector</li></ol><h4>1. เพิ่ม schema ที่ทำให้รองรับการเก็บข้อมูลแบบ Vector</h4><p>ข้อดีของ PostgresSQL คือ มันสามารถเก็บข้อมูล Vector ได้ โดยเราสามารถกำหนดชนิดของข้อมูลเป็น Vectorในไฟล์ schema ได้เลย</p><pre># ไฟล์ schema.gql<br>type Game @table {<br>  title: String!<br>  description: String!<br>  descriptionEmbedding: Vector<br>}</pre><h4>2. เพิ่ม mutation ในการเขียนข้อมูลที่เป็น Vector</h4><p>หลังจากกำหนด schema ก็ได้เวลาเขียนมูลลงใน database</p><p><strong>2.1 มี embedding model ที่ใช้อยู่แล้ว</strong></p><p>กรณีที่เราอาจจะมี embedding model ที่ใช้อยู่แล้ว เช่น เราอาจจะใช้ OpenAIs text embedding models หรือ model ที่บริษัททำเอง เราสามารถแปลงข้อมูลให้เป็น vector embeddings ให้เรียบร้อย แล้วเขียนไฟล์ mutation เพื่อโยน embeddings ไปเก็บไว้ใน database เฉยๆก็ได้ ตามโค้ดตัวอย่างด้านล่าง</p><pre>mutation CreateNewGame(<br>  $title: String!, <br>  $description: String!, <br>  $descriptionEmbedding: Vector!<br>) {<br>  game_insert(data: {<br>    title: $title,<br>    description: $description,<br>    descriptionEmbedding: $descriptionEmbedding<br>  })<br>}</pre><p><strong>2.2 ใช้ Vertex AI vector embeddings จาก Firebase Data Connect</strong></p><p>ถ้าไม่อยากจะไปเรียก API เพื่อทำ embedding เอง Firebase ก็มี wrapper function ที่ช่วยให้เราทำ embedding ได้แบบง่ายๆ โดยเราสามารถใช้คำสั่ง _embed และกำหนด embedding model ที่ต้องการ เพื่อให้มันสร้าง embedding ให้แบบอัตโนมัติ ซึ่งตัว model ที่รองรับก็จะเป็น <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/embeddings/get-text-embeddings#supported-models">embedding models จาก VertexAI ทั้งหมด</a></p><pre>mutation CreateNewGame(<br>  $title: String!, <br>  $description: String!, <br>  $descriptionEmbedding: Vector!<br>) {<br>  game_insert(data: {<br>    title: $title,<br>    description: $description,<br>    descriptionEmbedding_embed: {<br>      model: &quot;textembedding-gecko@003&quot;<br>      text: $description<br>    }<br>  })<br>}</pre><p>ในตัวอย่างเราทำการ embed ตัว description ที่เป็น text ให้เป็น embeddings ด้วย textembedding-gecko@003</p><h4>3. เขียน query ให้รองรับการค้นหาด้วย Vector</h4><p>หลังจากทำการเก็บข้อมูล vector แล้ว เรามาเขียน query เพื่อทำการค้นหาแบบ vector similarity search กัน</p><pre>query SearchSimilarContent($query: String!, $limit: Int = 3)<br>@auth(level: PUBLIC) {<br>  games_descriptionEmbedding_similarity(<br>    compare_embed: {<br>      model: &quot;textembedding-gecko-multilingual@001&quot;<br>      text: $query<br>    }<br>    method: L2<br>    within: 2<br>    limit: $limit<br>  ) {<br>    ...DisplayGame<br>  }<br>}</pre><p>Firebase Data Connect จะสร้างฟังก์ชั่น similarity สำหรับทุกๆ field ที่เป็น vector โดยเราสามารถใช้ฟังก์ชั่นนี้ในการทำ similarity search ได้เลย เช่น games_descriptionEmbedding_similarity</p><p>ในส่วนของการแปลง query ที่ user พิมพ์เข้ามาให้เป็น embeddings เราสามารถเรียก compare_embed เพื่อให้ Firebase Data Connect แปลง query string เป็น embeddings ให้เราได้เลย โดยเราสามารถเลือก model จาก VertexAI ได้เช่นกัน ในที่นี้เราใช้ textembedding-gecko-multilingual@001 เพื่อให้การค้นหาของเรารองรับหลากหลายภาษา (multilingual) ได้</p><p>เราสามารถทำการทดสอบ endpoints ด้วยการใช้ VSCode Extensions (ดูวิธีในบทความที่แล้ว) โดยจะเห็นว่าเราระบุ query เป็นภาษาไทยยาวเป็นกิโล แต่ก็ยังคงได้ผลลัพธ์จาก database ที่เราเก็บไว้เป็นภาษาอังกฤษ ออกมาค่อนข้างตรงทีเดียว ✨</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IInPmlkiP2Hs-zMtz0Tjzw.png" /><figcaption>ผลลัพธ์การค้นหาข้อมูลด้วยข้อความภาษาไทย</figcaption></figure><p>ถือได้ว่า ทำมาครบมาก และสามารถนำไปปรับใช้ได้กับหลากหลาย use cases เลย</p><h3>ต่อกับ Firebase Genkit เพื่อทำ Similarity search ด้วย keyword จากรูปภาพ</h3><p>ใน demo ของเรา เราเพิ่มอีกฟีเจอร์เพื่อให้ user สามารถส่งรูปเข้ามา แล้วแอปจะไปค้นหาเกมที่เหมือนกันให้ ด้วยการใช้ Firebase Genkit เป็นตัวช่วยในการดึง keyword จากรูปออกมา ก่อนนำ keyword ที่ได้ไปค้นจาก database เพื่อหาเกมที่คล้ายกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpeS4Py2KZKr9goub4Se3A.png" /><figcaption>ตัวอย่างการค้นหาแบบ Similarity search ด้วย keyword จากรูปภาพ ใน demo</figcaption></figure><h4>รู้จัก Firebase Genkit</h4><p><a href="https://firebase.google.com/docs/genkit">Firebase Genkit</a></p><p><strong>Firebase Genkit</strong> เป็นเครื่องมือที่ช่วยให้เราสร้างแอป AI ได้ง่ายขึ้น จุดเด่นของมันคือ การทำงานได้กับ model ที่หลากหลาย ไม่จำกัดแค่ของ Google พร้อมกับเราสามารถกำหนดโครงสร้างข้อมูลได้ เพื่อให้คำตอบที่ได้จาก Generative AI มี structure มากขึ้น</p><h4>ทำ Similarity search ด้วย keyword จากรูปภาพ</h4><p>เหมือนที่บอกไว้ในตอนต้นว่า เราจะส่งรูปไปให้ Gen AI ดึง keyword ออกมาให้ (ผ่าน Firebase Genkit) ก่อนนำ keyword ที่ได้ไปค้นจาก database ของเราเพื่อหาเกมที่คล้ายกัน</p><p><strong>0. ติดตั้ง Firebase Genkit</strong></p><p>ก่อนอื่นเลย เราจะต้องติดตั้ง Firebase Genkit ก่อน ตาม Document นี้</p><p><a href="https://firebase.google.com/docs/genkit/get-started">Get started | Genkit | Firebase</a></p><p>แล้วใช้คำสั่ง เพื่อเพิ่ม Genkit ที่รันบน Cloud Functions for Firebase ลงในโปรเจคของเรา</p><pre>firebase init genkit</pre><p>หลังจากที่เราติดตั้งเรียบร้อย เราจะได้โฟลเดอร์ functions มา แบบนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zk7_bR1asdt_Lxlca5c-SQ.png" /></figure><p>โดยจะมี source code ตัวอย่าง ในการใช้งานเบื้องต้นทั้งการ configGenkit รวมไปถึงตัวอย่าง flow ที่เราสามารถดูตัวอย่างการเขียนและลองทดสอบการทำงานเบื้องต้นได้</p><p><strong>Firebase Genkit</strong> ยังมี <a href="https://firebase.google.com/docs/genkit/devtools">Developer Tools</a> สำหรับการทดสอบ Flow, Model ต่างๆบน local ได้ด้วย โดยเราสามารถติดตั้งตาม Document นี้</p><p><a href="https://firebase.google.com/docs/genkit/devtools">Firebase Genkit Developer Tools</a></p><p>แล้วใช้คำสั่ง genkit start เพื่อเริ่มใช้งาน Developer UI อย่าลืมโหลด API key ที่จำเป็นก่อนรันด้วยน้า export GOOGLE_GENAI_API_KEY=&lt;your API key&gt; ถ้าเลือกใช้ GoogleAI สามารถกดรับ API key ได้ที่ <a href="https://aistudio.google.com/apikey">https://aistudio.google.com/apikey</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XTnpESi22oV4A9BjfF_lw.png" /><figcaption>หน้าตา Firebase Genkit Developer Tools</figcaption></figure><ol><li><strong>ทำ Flow ในการดึง keyword ออกมาจากรูป</strong></li></ol><p>ติดตั้งเครื่องมือที่จำเป็นเสร็จแล้ว เรามาเริ่มเขียน flow สำหรับ ดึง keyword จากรูปกัน การสร้าง flow ด้วย Firebase Genkit</p><pre>export const getKeywordFromPictureFlow = onFlow(<br>  {<br>    // Configuration ต่างๆของ Flow นั้น<br>  },<br>  async (input) =&gt; {<br>    // step การทำงานของ Flow เช่น<br>    // 1. เช็คว่ามีข้อมูล<br>    // 2. ส่งข้อมูลให้ GenAI ดึง keyword ออกมา<br>    // 3. ส่งผลลัพธ์กลับออกไปเป็น response<br>  }<br>);</pre><p>ส่วนประกอบของ Flow จะมีอยู่ 2 ส่วนด้วยกัน คือ</p><ul><li><strong>Configuration ต่างๆของ flow นั้น</strong> ที่ประกอบด้วย ชื่อ flow, schema ของ input/output, auth policy (Firebase Genkit ทำงานร่วมกับ Firebase Authentication ได้เป็นอย่างดี สามารถเช็คสิทธิ์การเข้าถึงแต่ละ flow ได้)</li></ul><pre>export const getKeywordFromPictureFlow = onFlow(<br>  {<br>    name: &quot;getKeywordFromPictureFlow&quot;,<br>    inputSchema: z.string(), // กำหนดให้รับ input มาเป็น string<br>    outputSchema: z.object({ // กำหนดว่า output ที่ได้จะอยู่ในรูปแบบของ {keywords: [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]}<br>      keywords: z.array(z.string()),<br>    }),<br>    // ให้ User ที่ login แล้วเท่านั้นใช้งานได้ เพื่อจำกัดการใช้งาน GenAI ที่อาจมีค่าใช้จ่าย 💸💸 (หรือเงื่อนไขอื่นๆตามต้องการ) <br>    authPolicy: firebaseAuth((user) =&gt; {}), <br>    httpsOptions: {<br>      cors: true,<br>    },<br>  },<br>...</pre><ul><li><strong>Step การทำงานของ flow </strong>เหมือนการเขียน functions ทั่วไป เพื่อระบุว่าใน flow นี้มีการทำงานอะไรบ้าง</li></ul><pre>...<br>  async (input) =&gt; {<br>    // ส่งข้อมูล Input ให้ GenAI ดึง keyword ออกมา<br>    const llmResponse = await generate({<br>      // ระบุ model ที่ต้องการใช้งาน จะเป็น claude3Sonnet, llama31, gpt4o, ollama ก็ได้<br>      model: gemini15Flash, // เราเลือกใช้ gemini15Flash เพราะเป็น multimodal ที่ใช้งานกับรูปได้<br>      output: { <br>        format: &quot;json&quot;, // บอกว่าอยากได้ structure data ในรูปแบบของ json<br>        schema: z.object({ // กำหนด structure ของ output ที่ต้องการ<br>          keywords: z.array(z.string()),<br>        }),<br>      },<br>      // กำหนด prompt<br>      prompt: [<br>        // โยน input เข้าไปเป็น media<br>        { media: { url: input } }, <br>        // prompt ที่บอกให้ GenAI ดึง keyword ออกมาจากรูปให้<br>        // พยายามลดคำซ้ำซ้อน คำสร้อย เพื่อให้ได้ keyword ที่ตรงประเด็น<br>        // พร้อมกับ brief มันอีกรอบว่าให้ส่งกลับมาเป็น array<br>        {<br>          text: `<br>            From the picture suggest 3 keywords or theme, avoid the word &#39;game&#39;, &#39;board&#39; or other decorative words. <br>            Return the keywords as an array list. e.g. [&#39;strategy&#39;, &#39;cooperative&#39;, &#39;worker placement&#39;]<br>          `,<br>        },<br>      ],<br>      config: {<br>        temperature: 1,<br>      },<br>    });<br>    return llmResponse.output() as { keywords: string[] };<br>  }<br>);</pre><p>การใช้คำสั่ง onFlow เป็นการระบุว่า Flow นี้จะถูก <a href="https://firebase.google.com/docs/genkit/flows#cloud_functions_for_firebase">Deploy flow ด้วย Cloud Functions for Firebase</a> เหมือนเป็น functions อันนึงใน Cloud functions</p><p>ลองทดสอบ flow ใน Developer tools ก่อนนำไปใช้งานกับ UI โดยเราส่ง link ของรูปเกม MouseTrap เกมโปรดของเด็กที่บ้าน เข้าไปเป็น input และได้ output ออกมาในรูปแบบ object ตามที่กำหนดไว้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T1cZGtJA6RulaVcOktrACw.png" /></figure><p><strong>2. เรียกใช้ใน client</strong></p><p>เพื่อให้การทดสอบบน local ราบรื่น เราเพิ่ม functions เข้าไปใน config ของเราก่อน พร้อมกับเชื่อมต่อไปที่ Function emulators</p><pre>/* ไฟล์ lib/firebase.ts */<br><br>export const firebaseApp = initializeApp({<br>  // your config from Firebase console<br>})<br><br>const functions = getFunctions(firebaseApp)<br><br>if (import.meta.env.DEV) {<br>  connectFunctionsEmulator(functions, &#39;localhost&#39;, 5003)<br>  // ... บริการอื่นๆที่ใช้<br>}<br>export { functions }</pre><p>จากนั้นทำการเรียกใช้ function ด้วย httpsCallable เหมือนการเรียกใช้ callable functions ทั่วๆไปจาก Cloud Functions for Firebase เลย</p><pre>export const extractKeywordsFromImage = async (<br>  input: string,<br>): Promise&lt;{ keywords: string[] }&gt; =&gt; {<br>  try {<br>    const getKeywords = httpsCallable(functions, &#39;getKeywordFromPictureFlow&#39;)<br>    const keywords = await getKeywords(input)<br>    return keywords.data as { keywords: string[] }<br>  } catch (error) {<br>    throw error<br>  }<br>}</pre><p>นำไปประกอบร่างกับ UI logic</p><pre>const searchByImage = async (imageData?: string) =&gt; {<br>    if (!imageData) return<br>    isPending.value = true<br>    try {<br><br>      // Get keywords จากรูปภาพด้วย Genkit<br>      const keywordsFromImage = (await extractKeywordsFromImage(imageData)) as {<br>        keywords: string[]<br>      }<br><br>      // นำ keyword มาต่อกันเป็น string<br>      const imgQuery = keywordsFromImage.keywords.join(&#39; &#39;)<br><br>      // ส่งไป query กับ Firebase Data Connect<br>      const response = await searchSimilarContent({<br>        query: imgQuery,<br>        limit: 10,<br>      })<br><br>      // นำค่าที่ได้ไปใช้งานใน UI<br>      games.value = response.data<br>        .games_descriptionEmbedding_similarity as Game[]<br>    } catch (err) {<br>      console.error(&#39;searchByImage&#39;, error)<br>      if (err instanceof Error) error.value = err<br>    } finally {<br>      isPending.value = false<br>    }<br>  }</pre><p>เพียงเท่านี้ก็ได้ฟีเจอร์ค้นหาแบบ Similarity search ด้วย keyword จากรูปภาพมาใช้งานแล้ว 🎉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpeS4Py2KZKr9goub4Se3A.png" /></figure><h4>ส่งท้าย</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McMNlMfRTrAgBmTT4zn7lA.jpeg" /></figure><p>เนื้อหาในบทความนี้มาจากสิ่งที่เราพูดไปในงาน Google DevFest Bangkok 2024 หัวข้อ Build better AI-driven Cloud SQL apps with Firebase Data Connect สิ่งที่ยกตัวอย่างมาทั้งหมดเป็นเพียงแค่ 1 ในหลาย use cases ที่เราสามารถนำ Firebase Data Connect และ Firebase Genkit บริการใหม่ทั้ง 2 ตัวจาก Firebase ไปเป็นตัวช่วยในการเพิ่มฟีเจอร์ AI ให้แอปพลิเคชันของเรา แบบสะดวกและง่ายที่สุด ใครลองใช้แล้ว อย่าลืมมาแบ่งปันให้กันฟังที่ <a href="https://www.facebook.com/groups/FirebaseDevTh/">Firebase Developer Group Thailand</a> บ้างนะคะ</p><p>อ่านมาถึงตรงนี้ ฝากกด <em>Clap</em> กด <em>Share </em>หรือกดติดตาม <a href="https://medium.com/firebasethailand">Firebase Thailand</a> เพื่อไม่ให้พลาดบทความต่อๆไปด้วยนะคะ สำหรับวันนี้ ขอบคุณและสวัสดีค่ะ 🙏</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d3364e81cea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebasethailand/%E0%B8%97%E0%B8%B3-vector-similarity-search-%E0%B8%81%E0%B8%B1%E0%B8%9A-firebase-data-connect-%E0%B9%81%E0%B8%A5%E0%B8%B0-firebase-genkit-9d3364e81cea">ทำ Vector similarity search กับ Firebase Data Connect และ Firebase Genkit</a> was originally published in <a href="https://medium.com/firebasethailand">Firebase Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bring Relational Power to Firebase with Firebase Data Connect]]></title>
            <link>https://medium.com/firebase-developers/bring-relational-power-to-firebase-with-firebase-data-connect-e65e5c420ca8?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e65e5c420ca8</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[firebase-database]]></category>
            <category><![CDATA[sql-database]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Tue, 03 Dec 2024 11:37:27 GMT</pubDate>
            <atom:updated>2024-12-17T15:26:53.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmCt4FU2oIqndlWc-Jv-tA.png" /><figcaption>This article has been translated from its original <a href="https://medium.com/firebasethailand/firebase-data-connect-%E0%B8%9A%E0%B8%A3%E0%B8%B4%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%97%E0%B8%B3%E0%B9%83%E0%B8%AB%E0%B9%89-firebase-%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B8%81%E0%B8%B1%E0%B8%9A-postgressql-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B9%86-43a3b0ff6141">blog post in Thai</a></figcaption></figure><p>Many of us are familiar with Firebase as a robust Backend-as-a-Service, renowned for its NoSQL databases such as Realtime Database (since 2012) and Cloud Firestore (since 2017). However, both have limitations when handling complex queries. The Firebase community has long been requesting a SQL database solution to address redundancy and facilitate complex queries.</p><p>At the recent Google I/O, Firebase introduced Firebase Data Connect, its first relational database offering 🎉</p><h3>How Firebase Data Connect Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLTQGzXCFGGTVuXvk-_1VQ.png" /><figcaption>App data flow</figcaption></figure><p>While Firebase Data Connect interacts with databases, it’s more accurately described as an interface. Under the hood, it’s leveraging PostgreSQL on GCP Cloud and providing a GraphQL-based bridge to connect clients with the SQL database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POGsEgp0V0Oti_BvrTe6Xg.png" /><figcaption>Firebase Data Connect capabilities that make working with PostgresSQL easier</figcaption></figure><p>The Firebase team built Data Connect with the philosophy of ‘You write the query, we do the rest.’ Developers only need to define two things, and Firebase handles the rest, allowing developers to focus on their application’s core logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOgrNje-L-rAKEMF_EKdrA.png" /><figcaption><strong><em>“You write the query, we do the rest”</em></strong></figcaption></figure><h4><strong>Firebase provides (in GraphQL):</strong></h4><ul><li><strong>Data model (schema):</strong> This specifies the database schema, including the tables, columns, and data types.</li><li><strong>Connectors (queries &amp; mutations):</strong> These define the operations for creating, reading, updating, and deleting data within the database.</li></ul><h4><strong>Firebase automatically creates:</strong></h4><ul><li><strong>PostgresSQL schema:</strong> Generates the SQL commands to create the database structure in PostgreSQL, including migrations.</li><li><strong>Type-safe SDK:</strong> Provides a strongly-typed SDK for client applications (iOS, Android, Web, Flutter) to interact with the database.</li><li><strong>API Endpoints:</strong> Creates API endpoints for clients to perform CRUD operations on the database, complete with authorization mechanisms to control user permissions. For instance, all users might be able to view product listings, but only admins can add new products.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ubdh2wWnIUP6F9xs3t9tw.png" /><figcaption>We define Data Model with GraphQL ➡ Firebase automatically generates SQL schema</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6ScWLe3emKSO0X4dRPFpg.png" /><figcaption>Queries and Mutations, defined via GraphQL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElCnMOpSrvW1PESVNVgM9Q.png" /><figcaption>Auto-generated API Endpoint from Firebase</figcaption></figure><h3>Getting started with Firebase Data Connect</h3><p>The process consists of 6 steps</p><pre>0. Set up the environment<br>1. Define the data model (schema)<br>2. Define the connector (queries, mutations)<br>3. Test locally<br>4. Integrate into the client app<br>5. Deploy to production</pre><h4>0. Set up the environment</h4><p>Firebase Data Connect can be initiated either through the user-friendly Firebase Console interface or by utilizing the command-line interface provided by the <a href="https://firebase.google.com/docs/cli">Firebase CLI</a>.</p><pre>firebase init dataconnect</pre><p>During the installation process, we’ll need to specify the Cloud SQL instance ID, database ID, and desired region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPQ1JhLV1YYJfkT-S744EQ.png" /><figcaption>Start a new Data Connect project using the command-line interface, and simultaneously set up a fresh Cloud SQL instance via Data Connect while it’s in public preview (eligible for a 3-month free trial).</figcaption></figure><p>As mentioned earlier, Firebase Data Connect is backed by Cloud SQL. To initialize the Data Connect via Firebase also means to create a Cloud SQL instance and a PostgreSQL database (if you haven’t already created one). Make sure your project is on the Blaze Plan (pay-as-you-go) before using this service.</p><p>During the public preview, creating a new database instance through Firebase Data Connect grants you a free 3-month trial of a Cloud SQL instance (db-f1-micro 1 vCPU, 600 MB RAM, and 10 GB storage). After the trial, standard pricing will apply based on instance size and usage. For detailed pricing, refer to the <a href="https://firebase.blog/posts/2024/11/dataconnect-pricing">Data Connect Pricing</a>.</p><p>After the setup is complete, you’ll have a Data Connect folder containing three components</p><ol><li><strong>connector folder</strong> for querying and mutating data.</li><li><strong>schema folder</strong> for defining the database data model.</li><li><strong>dataconnect.yaml file</strong> for the configuration.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ibh_5exyp6AYiWiOjcK_ng.png" /><figcaption>The dataconnect.yaml file stores various config information that we connect to CloudSQL.</figcaption></figure><h4>1. Define the data model (schema)</h4><p>Imagine we’re building an app for a board game store. The first thing we need to do is figure out how we want to organize all the data. Here’s an example of what this might look like using GraphQL in a file named schema.gql within the schema folder.</p><pre># schema.gql<br><br># Users<br>type User @table {<br>  id: String! @col(name: &quot;auth_uid&quot;)<br>  username: String! @col(name: &quot;username&quot;, dataType: &quot;varchar(50)&quot;)<br>}<br><br># Games<br>type Game @table {<br>  # The below parameter values are generated by default with @table, and can be edited manually.<br>  # implies directive `@col(name: &quot;game_id&quot;)`, generating a column name<br>  id: UUID! @default(expr: &quot;uuidV4()&quot;)<br>  title: String!<br>  description: String!<br>  imageUrl: String!<br>  genre: String<br>  emoji: String<br>  minAge: Int<br>  minPlayers: Int<br>  maxPlayers: Int<br>  playTime: Int<br>  descriptionEmbedding: Vector @col(size: 768) # Enables vector search<br>}<br><br># Reservations<br>type Reservation<br>  @table(name: &quot;reservations&quot;, key: [&quot;game&quot;, &quot;user&quot;, &quot;timeSlot&quot;]) {<br>  id: UUID! @default(expr: &quot;uuidV4()&quot;)<br>  user: User!<br>  game: Game!<br>  timeSlot: Timestamp!<br>  createAt: Date! @default(expr: &quot;request.time&quot;)<br>}</pre><p>Think of the user table as a list of all our players. The game table is a catalog of our games. The reservation table acts like a bridge between the two, showing which user has reserved which game and when. This table can have multiple foreign keys to connect to both the user and game tables, as shown in the code snippet.</p><h4>2. Define the connector (queries, mutations)</h4><p>This involves performing CRUD (Create, Read, Update, Delete) operations, such as retrieving or modifying data from the database. For example, in our board game store app, we might want to implement connectors as follows:</p><ul><li><strong>All users can search for board games, using keywords related to age and the number of players</strong></li></ul><p>The @auth(level: PUBLIC) directive specifies that this query is accessible to all users without requiring prior login.</p><pre># queries.gql<br><br>query SearchGames($keyword: String!, $minAge: Int, $player: Int)<br>@auth(level: PUBLIC) {<br>  games(<br>    where: {<br>      _and: [<br>        { minAge: { ge: $minAge } }<br>        { minPlayers: { le: $player } }<br>        { maxPlayers: { ge: $player } }<br>        {<br>          _or: [<br>            { title: { contains: $keyword } }<br>            { description: { contains: $keyword } }<br>            { genre: { contains: $keyword } }<br>          ]<br>        }<br>      ]<br>    }<br>  ) {<br>    ...DisplayGame<br>  }<br>}</pre><ul><li><strong>Users can only view their own reservations</strong></li></ul><p>The @auth(level: USER) directive ensures that only authenticated users can access this query. The eq_expr: &quot;auth.uid&quot; expression in the where clause utilizes the uid value from the provided auth token, enhancing security by eliminating the need for explicit uid parameters.</p><pre># queries.gql<br><br>query ListMyReservations @auth(level: USER) {<br>  reservations(where: { user: { id: { eq_expr: &quot;auth.uid&quot; } } }) {<br>    id<br>    game {<br>      ...DisplayGame<br>    }<br>    timeSlot<br>  }<br>}</pre><ul><li><strong>Only administrators can add new games</strong></li></ul><p>We can write an expression to check the token’s claims. For instance, if the token contains an isAdmin claim, we can verify that its value is true before granting the user permission to insert new game data into the database.</p><pre># mutations.gql<br><br>mutation CreateGame(<br>  $title: String!<br>  $description: String!<br>  ...<br>) @auth(expr: &quot;auth.token.isAdmin == true&quot;) {<br>  game_insert(<br>    data: {<br>      title: $title<br>      description: $description<br>      ...<br>    }<br>  )<br>}</pre><p>From the examples above, we can summarize the core concepts of creating connectors into 3 main parts:</p><ol><li><strong>Accepting parameters:</strong> We can pass parameters to queries to filter results. For example, specifying a minimum age to find suitable games.</li><li><strong>Defining access control:</strong> We can control access to endpoints using the @auth directive. We can either specify a predefined level or create custom expressions. If no @auth directive is provided, access is restricted to the Admin SDK by default. For more details on authorization, refer to <a href="https://firebase.google.com/docs/data-connect/authorization-and-security">Secure Data Connect with authorization and attestation</a>.</li><li><strong>Write SQL statements:</strong> including queries and mutations, following the GraphQL schema. Refer to the <a href="https://firebase.google.com/docs/reference/data-connect">Firebase Data Connect API Reference</a> for detailed instructions.</li></ol><p>While GraphQL is great for most queries, Firebase Data Connect also offers the flexibility to write raw SQL queries for more complex scenarios. This allows you to create custom database views tailored to your specific use case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8GeskBGKtCXFfKy-.png" /><figcaption><em>An example of using raw SQL to create a new view named “ReviewInfo” containing information about restaurants and their average reviews.</em></figcaption></figure><h4>3. Test locally</h4><p>Firebase Data Connect supports emulators, allowing for comprehensive local development and testing before deployment to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I762z7ERESUMYMETHJzAxw.png" /></figure><p><strong>3.1 Extensions<br></strong>To streamline a Data Connect workflow in VSCode or IDX, consider installing the Firebase Data Connect extension. This extension offers features like GraphQL autocompletion, a user interface for connecting to local emulators, and a tool for testing connections to our database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*hZzEJ6UqljJ0q40w.png" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=GoogleCloudTools.firebase-dataconnect-vscode">Firebase Data Connect extension for VSCode</a></figcaption></figure><p>Once we run the command</p><pre>firebase emulators:start</pre><p>We will see the Run (local) option. We could also go in DATA CONNECT EXECUTION tab to test the connection to our auto-generated API endpoints. After defining parameter variables and authentication, we can then click on “Run (local)” to test the endpoint locally or “Run (production)” to directly invoke the endpoint in the production environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQCTbSMKUBNXIZGFQqf_2g.png" /></figure><p>We can further customize the authentication process for each endpoint. For instance, we can define a rule for the SearchGame endpoint: @auth(level: USER_EMAIL_VERIFIED). This means only users with verified email addresses can access this endpoint. To test this scenario, we can configure the authentication settings during testing by setting the “Run as” to be “Authenticated” but with the email_verified flag set to false. When we run the test locally, we should receive a 401 Unauthorized error, confirming that the authentication requirement is enforced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbR0ARWV2vRcOBYYfiM1RQ.png" /></figure><p><strong>3.2 Data Seeding</strong><br>During local development, the database is cleared before each run. To pre-populate the database with some necessary data, we can create mutations to insert initial records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8hWCWP6eHrQwxBAA.png" /><figcaption>A file used to populate a database with initial game data</figcaption></figure><p>Once we’ve finished running the emulators, we can click “Run (local)” on this command to populate the initial data into our database.</p><p><strong>3.3 Exploring the data <br></strong>My SQL workflow typically involves tabular data visualization. While Firebase Data Connect currently lacks this feature, all output from testing each endpoint is simply returned in JSON format. As mentioned earlier, the underlying database is PostgreSQL, and Firebase uses PGLite for local execution, making tabular data viewing possible. We can utilize SQL viewers like DBeaver, DataGrip, or other preferred tools to establish a connection to jdbc:postgressql://127.0.0.1:5432/[databaseName]?sslmode=disable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*sWrsNA7MsEEgj4HJ.png" /><figcaption>Connection configuration for connecting to PostgresSQL locally with DBeaver</figcaption></figure><p>After that, we can look around at the data in each table and see how the database is structured, just like any other SQL database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ltXtYt1vv7zkrZ4-.png" /><figcaption>The ER Diagram of our database / The data we added to the Game table viewed through DBeaver</figcaption></figure><h4>4. Integrate into the client app</h4><p>I have put together a Vue web application as an example. It lists all the games and lets you search for specific ones using keywords like game name, age rating, or number of players.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*TBjN6euXc051WDWv.png" /><figcaption>The app UI after connecting with database</figcaption></figure><p>Having defined our data model and connectors, we’re ready to integrate them with our frontend. To streamline this process, we’ll leverage Firebase’s generated type-safe SDK instead of directly interacting with the database.</p><p>The connector.yaml file, generated during setup, determines the SDK’s destination and package name. Firebase will then create a customized SDK that can be seamlessly integrated into various client platforms including iOS, Android, Web, and Flutter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*HpfDTnu68slqW5OD.png" /></figure><p>All configurations will be initially commented out. We can uncomment and customize the settings according to our requirements. In this specific configuration, the output directory is set to the ‘app’ folder, corresponding to the Vue application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTg9zTM_6e9hZaKlwG5IUg.png" /></figure><p><strong>4.1 Connect UI with Data Connect Emulators</strong></p><pre>/* lib/firebase.ts */<br><br>export const firebaseApp = initializeApp({<br>  // your config from Firebase console<br>})<br>const auth = getAuth(firebaseApp)<br>const dataconnect = getDataConnect(firebaseApp, connectorConfig)<br>if (import.meta.env.DEV) {<br>  connectDataConnectEmulator(dataconnect, &#39;127.0.0.1&#39;, 9398, false)<br>  connectAuthEmulator(auth, &#39;http://localhost:9098&#39;)<br>}<br>export { auth, dataconnect }</pre><p><strong>4.2 Utilize functions and types provided by the SDK on the client-side</strong></p><pre>import { searchGames } from &#39;@dicely/dataconnect&#39;<br><br>const response = await searchGames({<br>  keyword: qParams.keyword,<br>  minAge: qParams.minAge ? Number(qParams.minAge) : undefined,<br>  player: qParams.player ? Number(qParams.player) : undefined,<br>})<br>/* ใช้ค่า response.data ใน UI <br> games.value = response.data.games as Game[]<br>*/</pre><p>As soon as we run this, it’ll automatically call the Firebase API endpoint and handle all the authentication stuff for us. It’s really this simple — just call the function and you’re good to go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*jPjyLEnrtFtVEU7s.png" /><figcaption>API Endpoint for searching game, auto-generated by Firebase</figcaption></figure><h4>5. Deploy to production</h4><p>Once we are satisfied with our local testing, we can execute the firebase deploy command to deploy the entire application or specifically deploy some product (e.g. dataconnect) to the production environment with</p><pre>firebase deploy --only dataconnect</pre><p>If there are any changes to our database that could potentially impact our production Firebase deployment, we will be notified beforehand. Alternatively, we can execute a command to review database changes before deploying.</p><pre>firebase dataconnect:sql:diff</pre><p>Once the deployment is complete, we can verify the data through the Firebase Console or inspect the Cloud SQL instance in the Google Cloud Console too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sqlYcEUQLlJfi-We.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-eURMftFXx_pLSRK.png" /><figcaption>We could explore the data in the Data Connect section of the Firebase Console or use Cloud Studio on Google Cloud Platform</figcaption></figure><h3>The workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vW5U91wf24gzERnO_G5O9w.png" /></figure><p>Whether developing for production or locally, our workflow as developers remains consistent:</p><ol><li>Define the data model and connectors using GraphQL.</li><li>Create an SDK for client-side usage.</li><li>Connect to the database via the client SDK.</li></ol><p>For those eager to experiment, feel free to check out this Codelab.</p><p><a href="https://firebase.google.com/codelabs/firebase-dataconnect-web?source=post_page-----43a3b0ff6141--------------------------------#0">Build with Firebase Data Connect</a></p><p>The content of this article is based on my talk, <em>Build better AI-driven Cloud SQL apps with Firebase Data Connect, </em>at Google DevFest Bangkok 2024<em>.</em> To make it easier to digest, I’ve decided to break it down into 2 parts. Stay tuned for Part 2, where we’ll be unlocking the full potential of Firebase Data Connect for building databases for AI-powered apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*usMuDzTEVaD2c8SZ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e65e5c420ca8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebase-developers/bring-relational-power-to-firebase-with-firebase-data-connect-e65e5c420ca8">Bring Relational Power to Firebase with Firebase Data Connect</a> was originally published in <a href="https://medium.com/firebase-developers">Firebase Developers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase Data Connect บริการที่ทำให้ Firebase เชื่อมต่อกับ PostgresSQL ได้แบบง่ายๆ]]></title>
            <link>https://medium.com/firebasethailand/firebase-data-connect-%E0%B8%9A%E0%B8%A3%E0%B8%B4%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%97%E0%B8%B3%E0%B9%83%E0%B8%AB%E0%B9%89-firebase-%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B8%81%E0%B8%B1%E0%B8%9A-postgressql-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B9%86-43a3b0ff6141?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/43a3b0ff6141</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[cloud-sql]]></category>
            <category><![CDATA[firebase-database]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 17:08:40 GMT</pubDate>
            <atom:updated>2024-12-03T10:50:14.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbhwwrBBfdHX30QXXgI2nw.png" /></figure><p>หลายคนคงคุ้นเคยกับ Firebase ในฐานะบริการ Backend as a Service ที่โดดเด่นด้วย NoSQL database อย่าง Realtime database ที่เปิดตัวมาตั้งแต่ปี 2012 และต่อยอดด้วย Cloud Firestore ในปี 2017 แต่ทั้งสองบริการยังมีข้อจำกัดในการจัดการ Query ที่ซับซ้อน เรามักจะได้ยินเสียงเรียกร้องจาก Firebase community อยู่เสมอว่า เมื่อไหร่จะมี SQL database สักที จะได้แก้ปัญหาเรื่องข้อมูลซ้ำซ้อนและทำ complex query ได้</p><p>ในที่สุดเมื่องาน Google I/O ที่ผ่านมา Firebase ก็เปิดตัว Firebase Data Connect ถือว่าเป็นบริการตัวแรกที่รองรับ Relational database ของ Firebase เลย 🎉</p><h3>การทำงานของ Firebase Data Connect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLTQGzXCFGGTVuXvk-_1VQ.png" /><figcaption>App data flow</figcaption></figure><p>จะบอกว่า Firebase Data Connect เป็น database ก็ไม่ถูกซะทีเดียว เพราะจริงๆแล้วเบื้องหลังของ Firebase Data Connect ก็คือ PostgresSQL ที่รันอยู่บน GCP Cloud โดยเจ้า Firebase Data Connect เป็นเหมือนตัวเชื่อมระหว่าง SQL Database กับ Client ให้เรา ด้วย GraphQL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POGsEgp0V0Oti_BvrTe6Xg.png" /><figcaption>ความสามารถของ Firebase Data Connect ที่ช่วยยกระดับให้การทำงานกับ PostgresSQL ง่ายขึ้น</figcaption></figure><p>ทีม Firebase สร้าง Firebase Data Connect ภายใต้คอนเซปที่ว่า <strong><em>“You write the query, we do the rest”</em></strong> นักพัฒนาอย่างเรากำหนดเพียง 2 อย่าง ส่วนที่เหลือ Firebase จะเป็นคนจัดการให้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOgrNje-L-rAKEMF_EKdrA.png" /><figcaption><strong><em>“You write the query, we do the rest”</em></strong></figcaption></figure><h4>สิ่งที่เรากำหนด (ในรูปแบบของ GraphQL)</h4><ul><li><strong>Data model (schema) </strong>ซึ่งเป็นการกำหนด database schema ว่าต้องมีตารางอะไรบ้าง แต่ละตารางต้องมีข้อมูลอะไร ชนิดไหนบ้าง</li><li><strong>Connector (queries &amp; mutations)</strong> ซึ่งก็คือ การ Create, Read, Update, Delete ข้อมูลใน database นั่นเอง</li></ul><h4>สิ่งที่ Firebase จะสร้างให้แบบอัตโนมัติ</h4><ul><li><strong>PostgresSQL schema</strong> คำสั่งสร้างโครงสร้างฐานข้อมูลใน PostgesSQL และ migration</li><li><strong>Typesafe SDK</strong> เพื่อใช้ใน client application ของเรา โดยรองรับทั้ง iOS, Android, Web และ Flutter</li><li><strong>API Endpoint</strong> เพื่อให้ client สามารถเชื่อมต่อ ทำ CRUD กับ Database ได้ พร้อมกับมี Authorization ที่จะคอยเช็คสิทธิ์ user ในทุกๆ endpoint อีกด้วย เช่น เราอาจจะอยากให้ user ทุกคนเห็นรายการสินค้า แต่เฉพาะ admin เท่านั้นที่เพิ่มรายการสินค้าได้ เป็นต้น</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ubdh2wWnIUP6F9xs3t9tw.png" /><figcaption>เรากำหนด Data Model ด้วย GraphQL ➡ Firebase สร้าง SQL schema ให้แบบอัตโนมัติ</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6ScWLe3emKSO0X4dRPFpg.png" /><figcaption>Queries และ Mutations ที่เรากำหนดผ่าน GraphQL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ElCnMOpSrvW1PESVNVgM9Q.png" /><figcaption>ตัวอย่าง API Endpoint ที่ Firebase สร้างให้</figcaption></figure><h3>เริ่มต้นใช้งาน Firebase Data Connect</h3><p>กระบวนท่าจะมีอยู่ 6 ขั้นตอนด้วยกัน ดังนี้</p><pre>0. ติดตั้ง<br>1. กำหนด Data model (schema)<br>2. กำหนด Connector (queries, mutations)<br>3. ทดสอบใน local<br>4. เรียกใช้ใน client<br>5. Deploy</pre><h4>0. ติดตั้ง</h4><p>เราสามารถเริ่มสร้าง Data Connect ได้ทั้งใน Firebase Console หรือ ใช้ command line ผ่าน <a href="https://firebase.google.com/docs/cli">Firebase cli</a> ด้วยคำสั่ง</p><pre>firebase init dataconnect</pre><p>ในการติดตั้ง เราต้องกำหนด ID ของ CloudSQL instance, ID ของ database, region ที่ต้องการ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPQ1JhLV1YYJfkT-S744EQ.png" /><figcaption>init dataconnect ผ่าน command line (init โดยการสร้าง CloudSQL ใหม่ตอนนี้ ได้ใช้ฟรี 3 เดือน)</figcaption></figure><p>อย่างที่ระบุไว้ต้นบทความว่า เบื้องหลังของ Firebase Data Connect เป็น CloudSQL ดังนั้นการสร้างตรงนี้คือการสร้าง CloudSQL instance และ PostgresSQL Databaseโดยโปรเจคของเราจะต้องเป็น <strong><em>Blaze Plan (Pay as you go) </em></strong>เท่านั้น ใครจะใช้อย่าลืมไปเปิด billing กันก่อนด้วยนะคะ</p><p>ในช่วง public preview นี้ ถ้าใครสร้าง database instance ใหม่ ผ่าน Firebase Data Connect ก็จะได้ใช้งาน CloudSQL instance แบบฟรีๆไป 3 เดือนเต็ม (ซึ่งจะเป็นตัว <strong>db-f1- micro</strong> 1 vCPU, 600 MB RAM and 10 GB storage)<em> </em>หลังจากนั้นคิดค่าใช้บริการตามจริง ขึ้นอยู่กับขนาด instance และจำนวนการใช้งาน ดูรายละเอียดราคาแบบเจาะลึกที่ <a href="https://firebase.blog/posts/2024/11/dataconnect-pricing">Data Connect Pricing</a></p><p>หลังจาก setup เสร็จเราจะได้โฟลเดอร์ data connect ที่มีส่วนประกอบ 3 ส่วน</p><ol><li>โฟลเดอร์ connector ซึ่งจะเป็นส่วนที่เราเรียกข้อมูลมาใช้ (Query) หรือแก้ไขข้อมูล (Mutation)</li><li>โฟลเดอร์ schema เป็นส่วนที่เรากำหนด Data model ของข้อมูลใน Database</li><li>ไฟล์ dataconnect.yaml เป็น config เมื่อกี๊ที่เราใส่เข้าไปตอน set up</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ibh_5exyp6AYiWiOjcK_ng.png" /><figcaption>ไฟล์ dataconnect.yaml เก็บข้อมูล config ต่างๆที่เราเชื่อมต่อกับ CloudSQL</figcaption></figure><h4>1. กำหนด Data model (schema)</h4><p>สมมุติว่าเราต้องการทำแอปร้านบอร์ดเกม สิ่งที่เราต้องทำคือกำหนดรูปแบบฐานข้อมูล หน้าตาประมาณนี้ด้วย GraphQL ที่ไฟล์ schema.gqlในโฟลเดอร์ schema</p><pre># schema.gql<br><br># Users<br>type User @table {<br>  id: String! @col(name: &quot;auth_uid&quot;)<br>  username: String! @col(name: &quot;username&quot;, dataType: &quot;varchar(50)&quot;)<br>}<br><br># Games<br>type Game @table {<br>  # The below parameter values are generated by default with @table, and can be edited manually.<br>  # implies directive `@col(name: &quot;game_id&quot;)`, generating a column name<br>  id: UUID! @default(expr: &quot;uuidV4()&quot;)<br>  title: String!<br>  description: String!<br>  imageUrl: String!<br>  genre: String<br>  emoji: String<br>  minAge: Int<br>  minPlayers: Int<br>  maxPlayers: Int<br>  playTime: Int<br>  descriptionEmbedding: Vector @col(size: 768) # Enables vector search<br>}<br><br># Reservations<br>type Reservation<br>  @table(name: &quot;reservations&quot;, key: [&quot;game&quot;, &quot;user&quot;, &quot;timeSlot&quot;]) {<br>  id: UUID! @default(expr: &quot;uuidV4()&quot;)<br>  user: User!<br>  game: Game!<br>  timeSlot: Timestamp!<br>  createAt: Date! @default(expr: &quot;request.time&quot;)<br>}</pre><ul><li>ตาราง user เก็บข้อมูลของผู้ใช้งานนั้นๆเอาไว้</li><li>ตาราง game เก็บข้อมูลและรายละเอียดต่างๆของเกม</li><li>ตาราง reservation เป็นตารางที่ join ข้อมูล Game และ User เอาไว้ด้วยกัน พร้อมกับเวลาที่จอง โดยเราสามารถกำหนด foreign key หลายๆอันได้อย่างที่ระบุใน code snippet ด้านบน</li></ul><h4>2. กำหนด Connector (queries, mutations)</h4><p>เป็นการทำ CRUD (Create, Read, Update, Delete) ไม่ว่าจะเป็นการดึงข้อมูลออกมา หรือแก้ไขข้อมูล จาก database ยกตัวอย่าง ในแอปร้านบอร์ดเกมของเรา เราอาจจะอยากให้มี connector ตามนี้</p><ul><li><strong>User ทุกคนสามารถ ค้นหารายการของบอร์ดเกมด้วย keyword อายุ และ จำนวนผู้เล่น</strong></li></ul><p>คำสั่ง @auth(level: PUBLIC) เป็นการระบุว่า ให้ทุกคนเข้าถึง query นี้ได้โดยไม่ต้องมีการ login ก่อน</p><pre># queries.gql<br><br>query SearchGames($keyword: String!, $minAge: Int, $player: Int)<br>@auth(level: PUBLIC) {<br>  games(<br>    where: {<br>      _and: [<br>        { minAge: { ge: $minAge } }<br>        { minPlayers: { le: $player } }<br>        { maxPlayers: { ge: $player } }<br>        {<br>          _or: [<br>            { title: { contains: $keyword } }<br>            { description: { contains: $keyword } }<br>            { genre: { contains: $keyword } }<br>          ]<br>        }<br>      ]<br>    }<br>  ) {<br>    ...DisplayGame<br>  }<br>}</pre><ul><li><strong>User สามารถดูการจองของตัวเองเท่านั้น (My reservations)</strong></li></ul><p>คำสั่ง @auth(level: USER) เป็นการระบุว่าต้อง login ก่อนเท่านั้นถึงจะเข้าถึง query นี้ได้ ใช้คำสั่ง eq_expr: &quot;auth.uid&quot; ใน where เพื่อใช้ค่า uid จาก auth token ที่ส่งเข้ามา แทนที่จะต้องรับค่า uid เป็น parameters เพื่อความปลอดภัยไปอีกขั้น</p><pre># queries.gql<br><br>query ListMyReservations @auth(level: USER) {<br>  reservations(where: { user: { id: { eq_expr: &quot;auth.uid&quot; } } }) {<br>    id<br>    game {<br>      ...DisplayGame<br>    }<br>    timeSlot<br>  }<br>}</pre><ul><li><strong>Admin เท่านั้น ที่สามารถเพิ่มเกมใหม่ได้</strong></li></ul><p>เราสามารถเขียน expression เพื่อตรวจสอบ token ที่อยู่ใน Auth ได้ด้วย เช่น กรณีนี้ เราอาจจะเก็บค่า isAdmin ไว้ใน token แล้วก็ตรวจสอบว่าค่าต้องเป็น auth.token.isAdmin == true ก่อนจึงจะอนุญาตให้ผู้ใช้มีสิทธิ์ insert ข้อมูลเกมลงใน database</p><pre># mutations.gql<br><br>mutation CreateGame(<br>  $title: String!<br>  $description: String!<br>  ...<br>) @auth(expr: &quot;auth.token.isAdmin == true&quot;) {<br>  game_insert(<br>    data: {<br>      title: $title<br>      description: $description<br>      ...<br>    }<br>  )<br>}</pre><p>จากตัวอย่างด้านบน ทุกคนน่าจะเห็นรูปแบบการเขียน connector แบบคร่าวๆแล้ว โดยสรุปได้ 3 อย่างด้วยกัน</p><ol><li><strong>รับค่า parameters ที่ต้องการ</strong> เช่น minAge ในการ ค้นหาเกม ที่เหมาะกับอายุของผู้เล่น</li><li><strong>กำหนดสิทธิ์ในการเข้าถึงข้อมูล</strong> อย่างที่เห็นในตัวอย่างด้านบน เราสามารถกำหนดการเข้าถึงของแต่ละ endpoint ได้ สามารถเลือกเป็น @auth(level: ...) หรือเขียนเงื่อนไขโดยการใช้ @auth(expr: ...)ถ้าไม่มีการกำหนด @auth(...) จะ default เป็น NO_ACCESS คือไม่ให้ใครเข้าถึงเลย นอกจากสิทธิ์ Admin SDK เท่านั้น ดูรายละเอียดเพิ่มเติมเกี่ยวกับ Auth ได้ที่ <a href="https://firebase.google.com/docs/data-connect/authorization-and-security">Secure Data Connect with authorization and attestation</a></li><li><strong>เขียนคำสั่ง SQL </strong>ไม่ว่าจะเป็น query หรือ mutation ตามรูปแบบ GraphQL ดู Ref คำสั่งได้ที่ <a href="https://firebase.google.com/docs/reference/data-connect">Firebase Data Connect API Reference</a></li></ol><p>นอกจากนี้ ถ้าเรามีคำสั่งที่ค่อนข้างซับซ้อน เขียน GraphQL แล้วอาจจะงง Firebase Data Connect ยังรองรับการเขียน Raw SQL Query ด้วย โดยเราสามารถสร้าง view ตาม query ที่เราต้องการได้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RIGjKi1K-FmIXOoEJw2Bg.png" /><figcaption>ตัวอย่างการใช้ Raw SQL เพื่อสร้าง view ใหม่ที่มีข้อมูล ReviewInfo (ร้านอาหารและค่าเฉลี่ยรีวิว)</figcaption></figure><h4>3.ทดสอบใน local</h4><p>Firebase Data Connect รองรับการทำงานกับ Emulators ด้วย ทำให้เราสามารถทำทุกอย่างบน local ให้มั่นใจก่อนการ deploy ไป production ได้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuuqIgHTHfdANNrRTWhjJQ.png" /></figure><p><strong>3.1 Extensions</strong></p><p>สำหรับใครที่ใช้ VSCode หรือ IDX สามารถติดตั้ง extentions เพื่อเพิ่มความสะดวกสบายในการทำงานกับ Data Connect ทั้ง auto complete ของ GraphQL, UI สำหรับการเชื่อมต่อกับ local emulators, UI สำหรับทดสอบ การเชื่อมต่อกับ endpoint ต่างๆ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E9VdsHF23udMHa3PTG0wyg.png" /><figcaption><a href="https://marketplace.visualstudio.com/items?itemName=GoogleCloudTools.firebase-dataconnect-vscode">Firebase Data Connect extensions สำหรับ VSCode</a></figcaption></figure><p>หลังจากที่เราใช้คำสั่ง</p><pre>firebase emulators:start</pre><p>เราจะเห็นว่ามีคำสั่ง Run (local) โผล่ขึ้นมา ซึ่งเราสามารถใช้ tab DATA CONNECT EXECUTION ในการทดสอบการเชื่อมต่อกับ endpoint ที่เราสร้างไว้ได้ โดยกำหนด Parameter variables และ Authentication แล้วกด Run (local) เพื่อทำการทดสอบ endpoint ใน local หรือกด Run (Production) เพื่อเรียก endpoint ใน production เลยนั่นเอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2W-g6nchrwglF0U0kabiw.png" /><figcaption>วิธีการใช้ VSCode Extentions ในการทดสอบ endpoint ของ Firebase Data Connect</figcaption></figure><p>เรายังสามารถแก้ไข Authentication ในการทดสอบสิทธิ์เข้าถึงของแต่ละ endpoint ด้วย อย่างเช่น SearchGame นี้เราลองกำหนดเล่นๆว่า @auth(level: USER_EMAIL_VERIFIED) หมายความว่าต้องเป็น user ที่มีการยืนยันอีเมลล์แล้วเท่านั้นจึงจะใช้ endpoint ได้ ในช่วงของการทดสอบ เราไปตั้งค่า Authentication โดยการกำหนด Run As ให้เป็น Authenticated แต่เปลี่ยนค่า email_verified จาก true เป็น false พอกด Run (local) เพื่อทดสอบ endpoint นี้อีกครั้ง เราจะได้ error กลับมาเป็นสถานะ 401 Unauthorized ทันที เพราะไม่เข้าเงื่อนไขที่กำหนดเอาไว้นั่นเอง</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7maRuoNzXbTcAwp5G72Jlg.png" /><figcaption>เราสามารถแก้ไข Authentication ในการทดสอบสิทธิ์เข้าถึงของแต่ละ endpoint ด้วย</figcaption></figure><p><strong>3.2 Seed data</strong></p><p>เวลาที่เราทำงานใน local ข้อมูลใน database จะถูก reset ใหม่ทุกรอบเวลาเรารัน emulators แต่ละครั้ง เพื่อความสะดวกสบายในการทำงานบน local เราสามารถเขียน mutation เพื่อเพิ่มข้อมูลลงใน database ได้ด้วย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8PxyJaom7gJ8N_p8TaFhg.png" /><figcaption>ไฟล์ seed สำหรับ seed ข้อมูลเกมต่างๆ</figcaption></figure><p>โดยหลังจากที่เรา run emulators เสร็จแต่ละครั้งเราก็สามารถมา Run (local) คำสั่งนี้ต่อได้เพื่อทำการ seed ข้อมูลเข้า database</p><p><strong>3.3 Exploring the data</strong></p><p>ความคุ้นชินของเราอย่างนึงในการทำงานกับ SQL คือการได้ดูข้อมูลในรูปแบบตาราง ซึ่งตอนนี้ Firebase Data Connect ยังไม่มีให้ ทุกอย่างที่พ่นออกมา จากการทดสอบแต่ละ endpoint ยังเป็นแค่ข้อมูลในรูปแบบ json เท่านั้น</p><p>อย่างที่บอกไปในตอนแรกว่าเบื้องหลังของมันคือ PostgresSQL และ Firebase ใช้ PGLite ในการรัน database บน local ซึ่งก็ทำให้การดูข้อมูลแบบตารางเป็นเรื่องที่ทำได้เหมือนกัน โดยเราสามารถใช้ SQL Viewer อย่าง DBeaver, DataGrip หรือเจ้าอื่นๆที่สะดวก แล้วสร้างการเชื่อมต่อไปยัง jdbc:postgressql://127.0.0.1:5432/[databaseName]?sslmode=disable</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBG6ctudJ0NzI1zYP1ySCg.png" /><figcaption>connection configuration สำหรับการเชื่อมต่อกับ PostgresSQL บน local ด้วยโปรแกรม DBeaver</figcaption></figure><p>หลังจากนั้น เราก็สามารถ explore ข้อมูลแต่ละตาราง ดู database schema ได้เหมือน SQL อื่นๆเลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twtaOncidYSFofWJtF5Ukg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5YEgqgxzwk7anl4hsk2Vg.png" /><figcaption>ER Diagram ของ Database ของเรา / ข้อมูลที่เราเพิ่มเข้าไปในตาราง Game ดูผ่าน DBeaver</figcaption></figure><p><strong>4. สร้าง SDK</strong></p><p>หลังจากที่เรากำหนดรูปแบบข้อมูลและ connector ที่ต้องการแล้ว ก็ถึงเวลาเอามาต่อกับ client หน้าบ้าน ซึ่งแทนที่เราจะไป connect กับ database ตรงๆ เราจะเชื่อมต่อกับ typesafe SDK ที่ Firebase สร้างให้ แบบเราเกริ่นเอาไว้ตอนแรก</p><p>ถ้าสังเกตตอนที่เรา firebase init dataconnect ในขั้นตอน 0.ติดตั้ง ในโฟลเดอร์ connectorมันจะมีไฟล์ connector.yaml ซึ่งไฟล์นี้แหละที่เราสามารถมากำหนด destination ของ SDK ที่เราต้องการ พร้อมกับตั้งชื่อ package เพื่อให้ Firebase ทำการสร้าง typesafe SDK ที่เราสามารถนำไปเรียกใช้ใน client app ไม่ว่าจะเป็น iOS, Android, Web, Flutter ได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj0s1KS1oXsMjv2VBiNydg.png" /></figure><p>เข้ามาตอนแรกทุกอย่างจะถูก comment เอาไว้ ให้ทำการเอา comment ออกและเขียน config ที่ต้องการลงไปเลย อย่างในนี้ เราระบุว่า ให้ outputDir อยู่ใน folder app ซึ่งก็คือ vue app ที่เราสร้างเอาไว้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yezMy7pLURFwJhVwTmbLkA.png" /><figcaption>สิ่งที่เราได้ หลังจากกำหนดค่า connector.yaml แล้ว</figcaption></figure><h4>4. เรียกใช้ใน client</h4><p>ในบทความนี้ เราทำแอปตัวอย่างเป็น vue web application ที่แสดงรายการของเกมทั้งหมด พร้อมกับฟังก์ชันในการค้นหาเกมด้วย keyword, อายุ และ จำนวนผู้เล่น</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*is5kZ3GYXqaGH1scfJLQfA.png" /><figcaption>หน้าตาแอปหลังจากเชื่อมต่อกับ database แล้ว</figcaption></figure><p><strong>4.1 เชื่อมต่อกับ Data Connect Emulators</strong></p><pre>/* ไฟล์ lib/firebase.ts */<br><br>export const firebaseApp = initializeApp({<br>  // your config from Firebase console<br>})<br><br>const auth = getAuth(firebaseApp)<br>const dataconnect = getDataConnect(firebaseApp, connectorConfig)<br>if (import.meta.env.DEV) {<br>  connectDataConnectEmulator(dataconnect, &#39;127.0.0.1&#39;, 9398, false)<br>  connectAuthEmulator(auth, &#39;http://localhost:9098&#39;)<br>}<br>export { auth, dataconnect }</pre><p><strong>4.2 ใช้ functions และ types ใน SDK บน client</strong></p><pre>import { searchGames } from &#39;@dicely/dataconnect&#39;<br><br>const response = await searchGames({<br>  keyword: qParams.keyword,<br>  minAge: qParams.minAge ? Number(qParams.minAge) : undefined,<br>  player: qParams.player ? Number(qParams.player) : undefined,<br>})<br><br>/* ใช้ค่า response.data ใน UI <br> games.value = response.data.games as Game[]<br>*/</pre><p>ซึ่งพอเราลองรันดู ก็จะเห็นว่ามันมีการเรียก api endpoint ที่ Firebase สร้าง พร้อมกับมีการเช็คสิทธิ์ Authentication ให้ด้วย แบบที่เราไม่ต้องทำอะไรเลย นอกจากเรียก function เท่านี้เองจริงๆ 🫰</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Df8YB-JQoNvObr4AJFxDfQ.png" /></figure><h4>5. Deploy</h4><p>ถ้าเราเทสบน local แล้วแฮปปี้ เราสามารถรันคำสั่ง firebase deploy เพื่อทำการปล่อยของทั้งหมด ขึ้น production ได้ หรือจะเลือกเฉพาะ product ก็ได้เช่นเดียวกัน</p><pre>firebase deploy --only dataconnect</pre><p>ถ้าหาก database ของเรามีการเปลี่ยนแปลงที่อาจกระทบของบน production firebase ก็จะทำการแจ้งเตือนเราก่อน หรือเราสามารถใช้คำสั่ง เพื่อเรียกดูการเปลี่ยนแปลงของ database ก่อนทำการ deploy ก็ได้</p><pre>firebase dataconnect:sql:diff</pre><p>หลังจากที่ deploy เรียบร้อยแล้ว ก็สามารถเข้าไปทดสอบข้อมูลของเราผ่าน Firebase Console หรือดู Cloud SQL ที่ Google Cloud Console ได้เช่นกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ht8FMB7Rhcx4vyWehu_pHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGk1G4YBtHC2RuDRTg46hg.png" /><figcaption>ดูข้อมูลผ่าน Firebase Console ที่เมนู Data Connect หรือจะดูผ่าน Cloud Studio ใน Google Cloud Console ก็ได้</figcaption></figure><h3>The workflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwMgmORGqBnE0Wx1Z_rLDw.png" /></figure><p>ไม่ว่าจะเป็นการ dev เพื่อเอาขึ้น production หรือ บน local โฟล์วการทำงานของนักพัฒนาอย่างเราเหมือนกันเลยคือ</p><ol><li>เขียน GraphQL เพื่อกำหนด Data model และ Connector</li><li>สร้าง SDK ไปใช้กับ client</li><li>เชื่อมต่อกับ database ผ่าน client SDK</li></ol><p>สำหรับคนที่อ่านมาถึงตรงนี้ แล้วอยากจะไปลองเล่น ตามไปที่ Codelab ตัวนี้ได้เลยค่า จับมือทำตั้งแต่เริ่มจนจบเลย</p><p><a href="https://firebase.google.com/codelabs/firebase-dataconnect-web#0">Build with Firebase Data Connect</a></p><p>เนื้อหาในบทความนี้มาจากสิ่งที่เราพูดไปในงาน Google DevFest Bangkok 2024 หัวข้อ Build better AI-driven Cloud SQL apps with Firebase Data Connect เพื่อให้อร่อย ย่อยง่ายขึ้น เราขออนุญาตตัดจบไว้แค่นี้ก่อน และเดี๋ยวมีภาค 2 ที่เน้นการสร้าง Database สำหรับ AI ตามมาแบบไม่นานเกินรอค่า ฝากติดตามกันด้วยน้า</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*McMNlMfRTrAgBmTT4zn7lA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43a3b0ff6141" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebasethailand/firebase-data-connect-%E0%B8%9A%E0%B8%A3%E0%B8%B4%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%97%E0%B8%B3%E0%B9%83%E0%B8%AB%E0%B9%89-firebase-%E0%B9%80%E0%B8%8A%E0%B8%B7%E0%B9%88%E0%B8%AD%E0%B8%A1%E0%B8%95%E0%B9%88%E0%B8%AD%E0%B8%81%E0%B8%B1%E0%B8%9A-postgressql-%E0%B9%84%E0%B8%94%E0%B9%89%E0%B9%81%E0%B8%9A%E0%B8%9A%E0%B8%87%E0%B9%88%E0%B8%B2%E0%B8%A2%E0%B9%86-43a3b0ff6141">Firebase Data Connect บริการที่ทำให้ Firebase เชื่อมต่อกับ PostgresSQL ได้แบบง่ายๆ</a> was originally published in <a href="https://medium.com/firebasethailand">Firebase Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ทุกอย่างที่ต้องรู้ก่อนใช้ Firebase Local Emulator Suite กับ Cloud Firestore]]></title>
            <link>https://medium.com/firebasethailand/%E0%B8%97%E0%B8%B8%E0%B8%81%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B9%E0%B9%89%E0%B8%81%E0%B9%88%E0%B8%AD%E0%B8%99%E0%B9%83%E0%B8%8A%E0%B9%89-firebase-local-emulator-suite-%E0%B8%81%E0%B8%B1%E0%B8%9A-cloud-firestore-71e9d8941399?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/71e9d8941399</guid>
            <category><![CDATA[firestore]]></category>
            <category><![CDATA[firebase-emulator-suite]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Sun, 14 Jun 2020 12:22:21 GMT</pubDate>
            <atom:updated>2020-06-14T12:44:45.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1P5_TSIVMYDHNAve00d6BA.png" /></figure><p>ถึงแม้ว่าเครื่องมือสำหรับพัฒนาและทดสอบ Firebase app บน Local อย่าง Firebase Local Emulator Suite จะเปิดตัวมานานเป็นปีแล้ว แต่ด้วยความเป็น Serverless backend tools ของ Firebase ที่รวดเร็วปรู๊ดปร๊าด อาจทำให้หลายคนยัง dev on production กันอยู่ (คนจริงเค้าเทสงานบน production กัน ทุกคนรู้ ยูสเซอร์รู้ 😂)</p><p>ที่ผ่านมาข้อจำกัดของ Firebase Local Emulator Suite ก็คือ ทุกอย่างต้องทำผ่าน command line แต่คุณคะ เมื่ออาทิตย์ก่อนเพิ่งมีการเปิดตัว Firebase Emulator Suite UI ที่เหมือนยก Firebase Console มาอยู่ใน Local ทำให้เราบริหารจัดการข้อมูลต่างๆ ได้ง่ายขึ้นไปกว่าเดิมอีก แล้วเราจะไม่ใช้ได้หรออออ</p><p>บทความนี้ จะพาทุกคนไปลองใช้ Firebase Local Emulator Suite กับการทดสอบข้อมูลใน Cloud Firestore กัน</p><h4><strong>ทำไมต้องทดสอบบน Local?</strong></h4><ol><li><strong>ข้อมูลใน Production ยังคงปลอดภัย</strong> ข้อมูลทุกสิ่งแยกออกจากกัน จะไม่มีการเผลอไปลบข้อมูลของผู้ใช้อีกต่อไป</li><li><strong>สะดวกต่อการเขียนเทส </strong>เนื่องจากเราสามารถกำหนดเซทของข้อมูลตาม test case ได้เลยตามต้องการ</li><li><strong>ไม่มีค่าใช้จ่ายที่คาดไม่ถึง </strong>จากการเพิ่มข้อมูลที่มากเกินไป หรือการเรียกใช้ functions เกินความจำเป็นในขณะที่ทดสอบระบบ</li><li><strong>เขียน Security Rules ได้ง่ายขึ้น</strong> แก้ปุ๊บ เห็นผลปั๊บ ไม่ต้องไปกด deploy ให้เมื่อยมือ</li></ol><h4>#1 เริ่มต้นใช้งาน</h4><p>สำหรับการสร้างโปรเจคใหม่ (ที่ใช้ Firebase CLI ตั้งแต่ v.8.4.0 ขึ้นไป) จะมีตัวเลือกให้ set up emulator ตั้งแต่การทำ firebase init ซึ่งเราสามารถเลือก emulator สำหรับ product ที่ต้องการ พร้อมกับทำการเลือก port ให้แต่ละ product ได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTKvykqpf149_Jp5wgTHCQ.png" /></figure><p>หลังจากจบขั้นตอนการติดตั้ง ถ้าดูในไฟล์ firebase.json จะพบว่ามี config ในส่วนของ emulators เพิ่มเข้ามาด้วย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*FjBpo_UvQbk4hcOiP46IAA.png" /></figure><p>สำหรับโปรเจคที่ใช้ Firebase อยู่แล้ว สามารถรัน firebase emulators:start เพื่อเริ่มต้นใช้งานได้เลย โดยที่ไม่ต้องมี emulator config ในไฟล์ firebase.json ก็ได้ (ซึ่ง emulators จะรันบน default port ที่ Firebase กำหนดไว้)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*DedfPJga2rpwylRkLkn0eQ.png" /><figcaption>Firebase Local Emulator Suite — default ports</figcaption></figure><p>ถ้าหากต้องการแก้ไข port เราสามารถเพิ่ม emulator config ตามภาพก่อนหน้า เข้าไปในไฟล์ firebase.json หรือถ้าขี้เกียจพิมพ์เอง สามารถใช้คำสั่ง firebase init emulators แล้ว set up ผ่าน CLI ก็ได้เช่นเดียวกัน</p><h4>#2 เชื่อมต่อข้อมูลบน local เข้ากับ app</h4><p>ท่าง่ายๆ ก็คือ ก่อนจะเรียกใช้ Firestore ให้เช็ค location ก่อน ถ้าเป็น localhost ให้ทำการ config host ของ database โดยชี้ไปที่ host ของ Firestore ที่เราตั้งค่าไว้ในขั้นตอนที่แล้ว</p><pre>const db = firebase.firestore()<br>if (location.hostname === &quot;localhost&quot;) {<br>  db.settings({ host: &quot;localhost:4001&quot;, ssl: false })<br>}</pre><p>หรือจะเพิ่มค่า boolean มาสักตัวหนึ่งสำหรับเก็บ flag ว่าต้องการจะใช้ emulator มั้ย ไว้กับ firebase config แล้วเช็คจากค่านั้นแทนการเช็ค location</p><pre>import firebase from &#39;firebase/app&#39;<br>import &#39;firebase/firestore&#39;<br>import config from &#39;./firebase-config&#39;</pre><pre>firebase.initializeApp(config)</pre><pre>if (config.useEmulator === true) {<br>  firebase.firestore().settings({ <br>    host: &#39;localhost:4001&#39;, ssl: false <br>  })<br>}</pre><p>วิธีนี้จะทำให้เราไม่ต้องมาคอย comment code ให้ linting tool อารมณ์เสีย ตอนที่อยากสลับไปเทสข้อมูลบน prodution ในบางที (แต่ไปสลับค่า flag แทน 😂)</p><h4>#3 start emulator</h4><p>สำหรับคนที่ทำ static website และใช้ Firebase Hosting สามารถใช้คำสั่ง firebase emulators:startเพื่อทำการ start local environment ให้กับทุก product ที่เลือกไว้ในขั้นตอนที่ #1 รวมถึงทำการ serve app ของตัวเองบน local ด้วย (แทนการเรียก firebase serve)</p><p>แต่สำหรับคนที่ใช้ Javascript framework อย่าง vue หรือ react ที่มี cli สำหรับ local environment อยู่แล้ว ไม่มีความจำเป็นที่จะให้ firebase serve app บน local ให้ สามารถใช้คำสั่ง--onlyเพื่อเลือกใช้ emulator แค่บางตัว เช่น firebase emulators:start --only firestore แล้วทำการรันคำสั่ง npm run serve หรือnpm start เพื่อ start app ของตัวเองในอีกหน้าต่างนึงของ terminal ตามปกติ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AN9nm8SCKrrzFpzN9ge8eg.png" /><figcaption>split terminal สำหรับการรัน Vue app และ emulator พร้อมกัน</figcaption></figure><p>ทุกครั้งที่เรา start emulator ใหม่ ข้อมูลใน database จะว่างเปล่าเสมอ ดังนั้นไม่ต้องตกใจ ถ้ารันมาแล้วข้อมูลใน app ของคุณหายไป</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*iER0IOiE8Hhr5gRzTRZ-Nw.png" /><figcaption>มันก็จะ blank blank หน่อย</figcaption></figure><p>เราสามารถทำการเพิ่มข้อมูลใน local ได้หลากหลายวิธี ไม่ว่าจะผ่าน Emulator Suite UI หรือจาก app เองโดยตรง และถ้าต้องการที่จะนำข้อมูลเหล่านั้นมาใช้ในการเทสครั้งถัดไป ก่อนที่จะปิดการใช้งานบน local (stop emulator) ให้ทำการ export ข้อมูลนั้นออกมาก่อน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bm385O5tRbzIn0PTJIZA9A.png" /><figcaption>ความดีงามของ Emulator Suite UI — เหมือนยกเอา Firebase Console มาไว้ใน local ยังไงอย่างนั้น</figcaption></figure><h4><strong>#4 export ข้อมูล</strong></h4><p>ก่อนที่เราจะทำการ stop emulator (Ctrl+C) เราสามารถเปิด terminal อีกหน้าต่างนึง เพื่อ export ข้อมูลที่เราเพิ่มไว้ออกมาก่อน ซึ่งสามารถทำได้ด้วยคำสั่ง</p><pre>firebase emulators:export [FOLDER_NAME]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*RsyXBPHyE6Q_vCPLaQyr6g.png" /><figcaption>มี log บอกทุกความเคลื่อนไหว</figcaption></figure><p>ซึ่งข้อมูลที่ได้จะเป็นโฟลเดอร์ที่ประกอบไปด้วย โฟลเดอร์ที่ชื่อว่า firestore_export และไฟล์ firebase-export-metadata.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*JXZ2PkNHUQTWUwMigtBVTQ.png" /><figcaption>โฟลเดอร์ที่ได้จากการ import</figcaption></figure><h4>#5 import ข้อมูลมาใช้</h4><p>ตอน start emulator เราสามารถนำเข้าข้อมูลที่เรา export ไว้ ด้วยคำสั่ง import ตามด้วยชื่อโฟลเดอร์ที่ต้องการ</p><pre>firebase emulators:start --only firestore --import [FOLDER_NAME]</pre><p>จะเห็นว่า สะดวกกับการสร้างชุดข้อมูล แล้ว import มาใช้ตาม test case ต่างๆ สุดๆ</p><h4>#6 นำข้อมูลจาก server มาใช้ใน local</h4><p>สำหรับคนที่เคย dev on production มาก่อน อาจจะต้องการนำข้อมูลใน Firestore บน cloud มาใช้ใน local ก็ทำได้เช่นกัน ด้วยการใช้ gcloud command line tool มาช่วย</p><p><a href="https://cloud.google.com/sdk/install">Installing Google Cloud SDK | Cloud SDK Documentation</a></p><p><strong>1. login แล้วเลือกโปรเจคที่ต้องการ</strong></p><pre>gcloud auth login<br>gcloud config set project [YOUR_PROJECT_ID]</pre><p><strong>2. export ข้อมูลใน Firestore ไปเก็บไว้ใน Cloud storage bucket </strong>(จะทำ Step นี้ต้อง enable billing ก่อนนะ)</p><pre>gcloud firestore export gs://[YOUR_PROJECT_ID].appspot.com/backup/firestore_export</pre><p>backup/firestore_export คือ path ที่เราต้องการจะเก็บ สังเกตก็คือเราจะตั้งชื่อให้มันคล้ายกับไฟล์ที่เรา export จาก emulator เพื่อให้ง่ายต่อการ import ใน step ถัดไปนั่นเอง</p><p><strong>3. ดาวน์โหลดไฟล์มาเก็บไว้ในเครื่อง</strong></p><pre>gsutil cp -r gs://[YOUR_PROJECT_ID].appspot.com/backup .</pre><p><strong>4. import ข้อมูลมาใช้เข้ามาใช้ใน local</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c9mlU_crHxP5Amq7OHqZxw.png" /></figure><p>ถ้าลองเปิดดูในโฟลเดอร์ที่ดาวน์โหลดมาจะเห็นว่า ไฟล์ที่ได้จะคล้ายๆกับไฟล์ที่เรา export มาจาก emulator เลย แต่เวอร์ชั่นที่เรา export มาจาก emulator จะมีไฟล์ firebase-export-metadata.json เพิ่มมาด้วย</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b48c8b6b4440df3e1742c593c268503/href">https://medium.com/media/3b48c8b6b4440df3e1742c593c268503/href</a></iframe><p>ดังนั้นให้ทำการเพิ่มไฟล์นี้เข้าไปใน folder backup ที่เราดาวน์โหลดมาก่อน ด้วยวิธีการที่ถนัดอย่าง copy แล้ว paste 😂 หรือจะ run script ที่ command line ด้วยคำสั่ง</p><pre>echo ‘{“version”:”8.4.2&quot;,”firestore”:{“version”:”1.11.4&quot;,”path”:”firestore_export”,”metadata_file”:”firestore_export/firestore_export.overall_export_metadata”}}’ &gt; backup/firebase-export-metadata.json</pre><p>พอมีไฟล์ firebase-export-metadata.json ในโฟลเดอร์ backup แล้วเราก็สามารถ import ข้อมูลเข้าไปใน emulator ด้วยคำสั่ง import ใน สเตปที่ #5 ได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*um5oimliwW4Pftr4aTGz6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5G-XMjWePGhK9BYnrMj1A.png" /><figcaption>ได้ข้อมูลจาก server มาแล้ว ข้อมูลไม่ blank อีกต่อปรัยยย</figcaption></figure><h4>#7 นำข้อมูลจาก local ไปใช้ใน server</h4><p>หรือกลับกัน สำหรับคนที่พัฒนาแบบ local first อาจจะมีความต้องการนำข้อมูลที่เราพัฒนาและทดสอบไว้แล้วใน local เข้าไปใช้ใน server ตอน deploy ระบบ ก็สามารถทำได้ด้วย gcloud command เช่นกัน</p><p><strong>1.อัพโหลดโฟลเดอร์ไปเก็บไว้ใน bucket </strong>ด้วยคำสั่ง</p><pre>gsutil cp -r [FOLDER_NAME] gs://[YOUR_PROJECT_ID].appspot.com/</pre><p><strong>2.นำข้อมูลเข้า Firestore</strong></p><pre>gcloud firestore import gs://[YOUR_PROJECT_ID].appspot.com/[FOLDER_NAME]/firestore_export</pre><p>อ่านเพิ่มเติมเกี่ยวกับการ export และ import data ได้ที่</p><p><a href="https://firebase.google.com/docs/firestore/manage-data/export-import">Export and import data | Firebase</a></p><p>ในขณะที่เขียนบทความนี้ Firebase Local Emulator Suite ยังอยู่ใน Beta stage ซึ่งเชื่อว่าถ้าเป็น GA เมื่อไหร่จะมีความดีงามที่มากกว่านี้แน่ๆ ถ้าใครยังไม่ได้ใช้มาลองใช้ด้วยกันนะคะ หรือใครที่ใช้อยู่แล้วเห็นว่าสามารถพัฒนาเพิ่มเติมได้ตรงไหน <a href="https://twitter.com/Firebase">ส่ง Tweet</a> ไปบอกกับทีม Firebase ได้น้า หรือจะส่งข้อความมาที่เพจ <a href="https://www.facebook.com/FirebaseThailand/">Firebase Thailand </a>ก็ได้ค่า เราพร้อมเป็นกระบอกเสียงให้คุณ สำหรับวันนี้ขอบคุณและสวัสดีค่า :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71e9d8941399" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebasethailand/%E0%B8%97%E0%B8%B8%E0%B8%81%E0%B8%AD%E0%B8%A2%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B8%97%E0%B8%B5%E0%B9%88%E0%B8%95%E0%B9%89%E0%B8%AD%E0%B8%87%E0%B8%A3%E0%B8%B9%E0%B9%89%E0%B8%81%E0%B9%88%E0%B8%AD%E0%B8%99%E0%B9%83%E0%B8%8A%E0%B9%89-firebase-local-emulator-suite-%E0%B8%81%E0%B8%B1%E0%B8%9A-cloud-firestore-71e9d8941399">ทุกอย่างที่ต้องรู้ก่อนใช้ Firebase Local Emulator Suite กับ Cloud Firestore</a> was originally published in <a href="https://medium.com/firebasethailand">Firebase Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[เขียน Codelab ของตัวเอง ด้วย Google Codelab tools]]></title>
            <link>https://medium.com/@naluinui/%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99-codelab-%E0%B8%82%E0%B8%AD%E0%B8%87%E0%B8%95%E0%B8%B1%E0%B8%A7%E0%B9%80%E0%B8%AD%E0%B8%87-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-google-codelab-tools-b9170a079292?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9170a079292</guid>
            <category><![CDATA[google-code-labs]]></category>
            <category><![CDATA[codelab]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Wed, 08 Apr 2020 10:28:02 GMT</pubDate>
            <atom:updated>2020-07-16T04:07:51.937Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VJPG5JlAItoA8UzrjLhBQ.png" /></figure><p>เนื่องจากสถานการณ์ Covid-19 ระบาดหนัก ทำให้ workshop ที่เราจะไปเป็น speaker ถูกย้ายมาทำบน online ทั้งหมด และเนื่องจากมันเป็น workshop ที่ผู้เข้าร่วมต้องลงมือทำจริงๆ ไม่ใช่แค่มานั่งฟังบรรยายแล้วจบ จะมา Live ทั้งวัน โดยที่ผู้ฟังต้องสลับหน้าจอไปเขียนโค้ดตามด้วยก็คงไม่เกิดประโยชน์ แถมคงสูบเน็ตคนฟัง สูบพลังคนพูดน่าดู… ด้วยความที่เคยใช้ Google Codelabs บ่อยๆ ก็ทำให้เกิดความคิดที่ว่า ถ้าทำ codelabs ได้แบบที่ Google ทำคงดีสินะ</p><p>เชื่อว่าหลายคนรู้จัก เคยเห็น หรือเคยใช้งาน Google Codelabs กันมาบ้างแล้ว Google Codelabs เป็นเว็บไซต์ที่รวบรวม tutorials เกี่ยวกับเทคโนโลยีต่างๆ ของ Google ผ่านตัวอย่างการสร้างแอปหรือเว็บไซต์เล็กๆตามขั้นตอน แต่ละขั้นตอนก็จะมีคำแนะนำต่างๆ ที่บอกว่าเราต้องทำอะไรบ้าง step-by-step ถือว่าเป็น tool สำหรับการเรียนรู้ด้วยตัวเองชั้นยอดเลยล่ะ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4RBcDcylkMrmQOvN3Gh5w.png" /></figure><p>พอมีไอเดียว่าอยากได้เว็บแบบ Google Codelabs ก็วางแผนไปไกลมาก (แต่มีเวลาแค่ 1 อาทิตย์ 😂) แทบจะเปิด vs code มาเขียนเว็บ codelab ของตัวเอง แต่แล้วก็เจอของดีย์! Google เค้ามี tools ให้ทำ codelab ของตัวเองจ้า ที่สำคัญไม่ต้องเขียนโค้ดเลยสักนิดอะเธอว์</p><h4>3 ขั้นตอนง่ายๆ</h4><ol><li>เขียน Codelab ตาม format ด้วย Markdown หรือ Google Docs</li><li>ใช้ claat command line แปลง Codelab ของเราให้เป็นหน้า html</li><li>Host ที่ไหนก็ได้ ตามใจชอบ</li></ol><h4>เขียน Codelab ให้ถูก Format</h4><p>ขั้นแรกนี้ Google มี format ให้ 2 แบบ คือจะเขียนแบบ Markdown ก็ได้ หรือจะเขียนด้วย Google Docs ก็ได้ ซึ่งแน่นอน<em> สมจินตนาเลือก Google Docs ค่ะ! </em>โดย Google ได้สร้าง <a href="https://docs.google.com/document/d/1E6XMcdTexh5O8JwGy42SY3Ehzi8gOfUGiqTiUX6N04o/edit">template</a> ไว้ให้แล้ว เราแค่ไป Make a copy แล้วมาแก้ไขเป็นเวอร์ชั่นของเราเองได้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Bn6-LDeyxkAYMOKoJd4tw.png" /></figure><p><strong>ส่วนประกอบต่างๆ</strong></p><ul><li><strong>หัวข้อ</strong> ต้องใช้ตัวอักษร <strong>Heading 1 </strong>สำหรับหัวข้อหลัก หัวข้อเหล่านี้จะถูกแปลงให้เป็นขั้นตอน (Step) ใน Codelab ที่แสดงอยู่ด้านซ้ายมือ ซึ่งเป็นเหมือนสารบัญที่ผู้เรียนสามารถเห็นภาพรวมของ Codelab ว่ามีเนื้อหาครอบคลุมเรื่องอะไรบ้าง และสามารถกดกระโดดข้ามไปข้ามมาในแต่ละขั้นตอนได้ตอนทำ Codelab</li><li><strong>เนื้อหา</strong> แน่นอนในแต่ละหัวข้อหลักเราจะมีรายละเอียดเนื้อหาอยู่ ใช้ตัวอักษร <strong>Normal text</strong> สำหรับเนื้อหา และถ้าต้องการแบ่งเป็นหัวข้อย่อยๆ ให้ใช้ตัวอักษร <strong>Heading 2, Heading 3, Heading 4 </strong>ตามลำดับ ซึ่งมันจะแปลงร่างเป็น tag &lt;h2&gt; &lt;h3&gt; &lt;h4&gt; ตอนเปลี่ยนเป็นหน้า html นั่นเอง</li><li><strong>รูป </strong>สำหรับการใส่รูปใน Codelab จาก Google Docs นั้นง่ายมาก ก็คือทำเหมือนแนบรูปปกติเลย ง่ายอะไรขนาดนั้นอะ</li><li><strong>กล่องข้อความ</strong> ถ้าเราต้องการเน้นย้ำข้อความบางอย่าง เราสามารถทำให้ข้อความนั้นเด่นขึ้นมาได้ด้วยการใช้กล่องข้อความ โดยการยัดข้อความเข้าไปในตารางแล้วเปลี่ยนสีพื้นหลังเป็นสีเขียวสำหรับข้อความที่มีความหมายเชิงบวก เช่น tip &amp; trick หรือสีเหลืองสำหรับข้อความ warning หรือข้อความที่มีความหมายเชิงลบอื่นๆ</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*iSHHRybFP2PyBfoRBSFywg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*hhN0vXyFVPHiF42MdaokzA.png" /><figcaption>กล่องข้อความใน Google Docs Format และกล่องข้อความที่แสดงผลใน Codelab</figcaption></figure><ul><li><strong>Code / Command line snippets </strong>เราต้องใช้ฟ้อนต์<strong> Courier New </strong>สำหรับข้อความที่เป็น code<strong> </strong>ทั่วไปและใช้ฟ้อนต์<strong> Consolas </strong>สำหรับข้อความที่เป็น<strong> </strong>command line<strong> </strong>โดยการแนบ code ใน Codelab จะมีอยู่ 2 รูปแบบด้วยกัน คือ การแนบ code แบบบรรทัดเดียว ซึ่ง code นั้นจะอยู่รวมกับข้อความอื่นๆ และ การแนบ code แบบหลายบรรทัด ก็จะเป็นกล่องข้อความที่มี code อยู่ข้างใน ซึ่งถ้าทำแบบบรรทัดเดียวเราแค่ทำการเปลี่ยน ฟ้อนต์ของข้อความในส่วนที่เป็น code ให้เป็น<strong> Courier New หรือ Consolas </strong>ตามต้องการ<strong> </strong>และถ้าทำแบบหลายบรรทัดก็แค่เอาข้อความนั้นไปยัดไว้ในตารางเหมือนกับการทำกล่องข้อความเลย แต่อย่าลืมนะ ฟ้อนต์ต้องเป็น <strong>Courier New หรือ Consolas </strong>เท่านั้น</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zESnwnFLEY1ISsr8AbbdPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-ID7DWUMulBZK5-v7TUqw.png" /><figcaption>Code / Command line snippets ใน Google Docs Format และใน Codelab</figcaption></figure><ul><li><strong>เวลา</strong> ถ้าสังเกต ตอนที่เราทำ Codelab มันจะมีข้อความที่บอกว่า เหลืออีกกี่นาทีจะทำ Codelab เสร็จ คอยให้กำลังใจเราอยู่ที่มุมขวาบน เราสามารถใส่เวลานั้นใน Codelab ของเราได้เช่นกัน โดยการเขียนเวลาของแต่ละขั้นตอนในรูปแบบ <strong>Duration: 01:00</strong> ด้วยฟ้อนต์สีเทาเข้มแค่นี้เลย พอแปลงร่างเป็น html เวลาทั้งหมดที่ต้องใช้ในการทำ Codelab จะถูกคำนวณให้โดยอัตโนมัติ</li><li><strong>Codelab Metadata</strong> เป็นอีกหนึ่งอย่างที่สำคัญและขาดไม่ได้! คือตารางสรุปรายละเอียดของ Codelab ซึ่งประกอบไปด้วย <strong>Summary</strong> (สรุปสั้นๆว่า Codelab มีเนื้อหาเกี่ยวกับอะไร), <strong>URL</strong> (ชื่อ path ที่จะทำให้ codelab เข้าถึงได้), <strong>Category</strong> (ประเภทของ codelab), <strong>Environment</strong> (Hardware ที่ใช้แสดงผล codelab), <strong>Status</strong> (สถานะของ Codelab), <strong>Feedback link</strong> (url ที่จะให้ผู้เรียนได้มาทิ้งคำถามหรือแจ้ง feedback ต่างๆเกี่ยวกับ codelab), <strong>Analytics Account</strong> (ถ้าต้องการ track analytics ของ codelab ก็ทำได้ด้วยการใส่ Google Analytics ID)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*TJS0_PXw7PAoOd-_glTzTw.png" /></figure><p>นอกจากนี้เรายังสามารถแนบวีดีโอ, ปุ่ม download, ลิสคำถามที่พบบ่อยที่สามารถลิ้งค์ไปยัง Stackoverflow และอื่นๆอีกเพียบ โดยสามารถเข้าไปดูรายละเอียดเพิ่มเติมที่ <a href="https://github.com/googlecodelabs/tools/blob/master/FORMAT-GUIDE.md">Codelab Formatting Guide</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*FrG7M00C8M0xNkkvBxaWxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*o54OvqTPD9OI5LsgJquH6g.png" /><figcaption>ส่วนประกอบต่างๆ ของ Codelab Format</figcaption></figure><p><strong>Preview<br></strong>หลังจากที่เขียน Codelab ใน Google Docs ไปสักพัก เราก็จะมีความอยากเห็นว่า codelab ของเราหน้าตาจะเป็นยังไงบ้างแล้วน้า… Google ได้เตรียม tool สำหรับ preview ไว้ให้แล้ว เป็น chrome extension ชื่อว่า <a href="https://chrome.google.com/webstore/detail/preview-codelab/lhojjnijnkiglhkggagbapfonpdlinji">Preview Codelab</a> วิธีใช้งานก็ง่ายมาก หลังจากที่เราติดตั้ง extension เรียบร้อย เราจะเห็นว่ามีปุ่ม Preview ขึ้นมาใน browser เพียงแค่เปิด Google Docs ที่เราเขียน Codelab ไว้และกดปุ่มนี้ เราก็จะสามารถเห็น Codelab ของเราในรูปแบบของ Google Codelab แล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gt8Nu9p98qOr21QxLDoTUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kYAdjSNE1UdKT7LObEVgKA.png" /></figure><h4>แปลงร่างเป็น HTML ด้วย claat (Codelab as a thing)</h4><p>เมื่อทุกอย่างพร้อม ก็ถึงขั้นตอนของการแปลง Codelab ที่อยู่ใน Google Docs ของเราให้เป็นหน้า html เสียที</p><p><strong>ติดตั้ง Codelabs command line tool </strong><br>อันดับแรก เราต้องทำการติดตั้ง command line tool ที่ชื่อว่า <a href="https://github.com/googlecodelabs/tools/tree/master/claat">claat</a> ก่อน โดยวิธีการติดตั้งก็แค่เข้าไปโหลด claat เวอร์ชั่นล่าสุดที่หน้า <a href="https://github.com/googlecodelabs/tools/releases/latest">Release Notes</a> หรือถ้าใครใช้ภาษา go อยู่ อยากติดตั้งผ่าน go ก็ได้เช่นกัน <a href="https://www.marcd.dev/codelab-4-codelab/#1">อ่านเพิ่มเติมได้ที่นี่เลย</a></p><p><strong>Execute permission</strong><br>ถ้าใครใช้ mac หลังจากโหลดแล้วก็จะต้องมีการ set ค่า execute permission ของไฟล์ ผ่าน command line กันนิดนึง โดยให้ cd ไปที่ directory ที่เก็บไฟล์นั้นไว้ แต่ก่อนอื่นแนะนำให้เปลี่ยนชื่อไฟล์ที่โหลดมาจากชื่อ claat-darwin-amd64 เป็น claat เฉยๆ ก่อน เพื่อให้ step ถัดไปของเราง่ายขึ้น จากนั้น run command ด้านล่างนี้เพื่อตั้งค่า execute permission</p><pre>chmod u+x claat</pre><p>เสร็จแล้วลอง run ไฟล์ claat อีกทีด้วย command</p><pre>./claat -h</pre><p>ถ้าเห็นหน้าตาแบบนี้ แปลว่า Codelabs command line tool ของเราพร้อมใช้งานแล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uiDNzWkObTKP4R4NaiXX2w.png" /></figure><p><strong>แปลง Google Docs เป็น HTML</strong><br>เราสามารถทำการแปลง Google Docs เป็นหน้าเว็บ HTML ด้วยคำสั่ง</p><pre>./claat export &lt;YOUR_GOOGLE_DOC_ID&gt;</pre><p>สังเกตว่าใช้แค่ Google Docs ID เท่านั้นเอง ซึ่ง ID นี้หาได้จาก url ของ Google Docs ของเราค่ะ หน้าตามันจะเป็นประมาณนี้ https://docs.google.com/document/d/<strong>&lt;YOUR_GOOGLE_DOC_ID&gt;</strong>/</p><p>หลังจากแปลงเสร็จจะมีโฟลเดอร์โผล่ขึ้นมาให้เราทันที ซึ่งถ้าเข้าไปดูก็จะเห็นว่ามีไฟล์ html, โฟลเดอร์ที่เก็บรูปที่เราแนบไว้ใน Codelab และ ไฟล์ json ที่เก็บรายละเอียดต่างๆ ของ Codelab พร้อมให้เราเอาไป publish ได้แล้ว</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*yLWRKMRqEGEhp3IQYfhldw.png" /></figure><h4>Host</h4><p>จังหวะนี้เราจะเอาไปหน้า html ของเราไป host ไว้ที่ไหนก็ได้ ซึ่งแน่นอนสมจินตนาเลือก <strong>Firebase Hosting</strong> เนื่องจากมันเร็ว เชื่อถือได้ มี ssl เรียบร้อย ได้พื้นที่ 1GB ฟรี แถมยังได้ url เท่ๆอย่าง &lt;project_name&gt;.web.app แบบไม่ต้องเสียตังสักบาทด้วย</p><p>เนื่องจาก เราได้สร้างโฟลเดอร์ที่รวม codelab แต่ละอันไว้แล้ว เราจะทำการ set up firebase project กันที่โฟลเดอร์นี้เลย โดยการ runfirebase init แล้วเลือก hosting เลือกการตั้งค่าตามภาพด้านล่าง ในที่นี้เราใช้ Firebase project ที่สร้างไว้แล้ว ถ้าใครยังไม่ได้สร้างจะสร้างผ่าน command ก็ได้ หรือจะไปสร้างจาก Firebase console ก็ได้เช่นเดียวกัน</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*Hy2boK5ux3uPgq39a8TMSQ.png" /></figure><p>หลังจากที่ตั้งค่าอะไรเรียบร้อย เราจะได้โฟลเดอร์ public มา เราก็จะทำการย้ายโฟล์เดอร์ของ codelab แต่ละอันเข้าไปอยู่ในโฟลเดอร์ public แทน เพื่อทำการ upload ขึ้น hosting ต่อไป จากนั้นทำการ run</p><pre>firebase deploy</pre><p>แค่นี้เราก็ได้ codelab ของเราเองที่คนอื่นสามารถเข้าถึงได้แล้ว! หน้าตาแบบนี้…</p><p><a href="https://naluinui.web.app/firebase-liff-pt3/">Part 3: Enhancing your LINE chatbot with LIFF x Firebase</a></p><p>Tip: จริงๆแล้วตอนเราใช้ claat เพื่อแปลงไฟล์ เราสามารถกำหนด output directory ให้มันได้ด้วยนะ ถ้าเรากำหนด output เป็น public ก็จะสะดวกมากสำหรับการ deploy ครั้งต่อๆไป</p><pre>./claat export -o public &lt;YOUR_GOOGLE_DOC_ID&gt;</pre><h4>ส่งท้าย</h4><p>นอกจากนี้ Google Codelabs tools ทำให้เราสามารถมีหน้า landing page ที่รวบรวม codelab ทั้งหมดของเราเองได้ด้วยนะ หน้าตาแบบนี้เลย</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgkLKBYHyz84G5zOPJc59Q.png" /></figure><p>ซึ่งจุดนี้เรายังไม่ได้ลองเลยค่ะ ถ้าลองแล้วจะมาแบ่งปันให้อ่านกันในบทความถัดไปนะคะ หรือถ้าใครรู้สึกคันไม้คันมืออยากทำตอนนี้เลย อ่านเพิ่มเติมที่<a href="https://github.com/googlecodelabs/tools/blob/master/site/README.md">นี่</a>ก่อนนะคะ</p><p>ถึงแม้ว่าสถานการณ์ Covid-19 ออกจะแย่ไปนิดนึงที่ทำให้เราต้องอยู่แต่บ้าน อดไปเจอหน้าหรือทำกิจกรรมร่วมกัน แต่อย่างน้อยก็ถือว่ามันเป็นโอกาสให้เราได้เรียนรู้สิ่งใหม่ๆ ลองทำในสิ่งที่ไม่เคยทำ พบเจอกับสิ่งที่ไม่เคยค้นหามาก่อน สุดท้ายนี้ก็ขอให้ทุกคนรักษาสุขภาพและสนุกกับโอกาสตรงนี้กันนะคะ แล้วพบกันใหม่ในบทความถัดไปค่ะ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9170a079292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase ML Kit Custom Models for iOS developers — Part 2: Implementing Tic Tac Toe]]></title>
            <link>https://medium.com/firebasethailand/firebase-ml-kit-custom-models-for-ios-developers-part-2-implementing-tic-tac-toe-44f1cd9f99c5?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/44f1cd9f99c5</guid>
            <category><![CDATA[ml-kit]]></category>
            <category><![CDATA[firebase-ml-kit]]></category>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 16:58:07 GMT</pubDate>
            <atom:updated>2020-01-07T10:55:24.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYC2F2ba2ARQIIzp6I5MxQ.png" /></figure><h3>Firebase ML Kit Custom Models for iOS developers — Part 2: Implementing Tic Tac Toe</h3><p>In <a href="https://medium.com/@naluinui/firebase-ml-kit-custom-models-for-ios-developers-part-1-understanding-tensorflow-lite-123dfcfdce29">Part 1</a>, we build a model to add 3 floating point numbers to understand how TensorFlow Lite model works with the Firebase ML Kit.</p><p>That model was never going to be used in a real app, so let’s consider a more realistic example. Let’s say you are building an app for playing Tic Tac Toe (a.k.a. Noughts and Crosses or OXO) and your app needs to suggest hints to the player or implement an AI.</p><p>Let’s create a TensorFlow Lite model that finds the best moves for a particular board state and use it inside our iOS app to score all the possible next moves that the player can make.</p><h4>Step 1: Inspect the model</h4><p>The Tic Tac Toe model takes a board state (3x3 grid of cells) and outputs the next move for every cell (so the output is also 3x3). It is a simple network with 2 hidden layers, trained on a million games played by 2 random players. Note that the model is not a perfect player! (I leave it to ML readers to retrain the model to be a better player — send me your results please)</p><p>You can recreate the dataset and retrain the model yourself in his <a href="https://colab.research.google.com/drive/1mVV-45hxSjNkVzY6uDcrq0UAn0KxqxYk">Tic Tac Toe Colab</a>. Or you can do like I did and jump straight to download the <a href="https://github.com/naluinui/mlkit-custom-model-ios/raw/master/mlkit-custom-model-ios/Resources/tictactoe.tflite">tictactoe.tflite</a> file.</p><p>Open the model in Netron again. You will see the layers and the inputs and outputs that we are interested in:</p><ul><li>Input type: float32[3,3]</li><li>Output type: float32[3,3]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*EVDREW6LRvT925zf5HZP8A.jpeg" /><figcaption>Inspecting the inputs/outputs of the tic tac toe model in Netron</figcaption></figure><p>How do we input X and O as floats? The way the model was built is that if the current player is O then the cells with O will be encoded as 1.0, and the opponent’s Xs will be encoded as -1.0. If the current player is X then this is reversed (Xs are 1.0 and Os are -1.0). The empty cells are always encoded as 0.0.​</p><p>For example, the board state:</p><pre>X|O|<br>-+-+-<br>X|O|O<br>-+-+-<br> | |X</pre><p>If the current player is O so input to the model would be:</p><pre>[[-1., 1., 0.],<br> [-1., 1., 1.],<br> [0., 0., -1.]]</pre><p>The output of the model is the same shape, where the value of each cell is how good the move is for the current player. Clearly the best move for O is the bottom middle cell, so you would hope that the model outputs similar to:</p><pre>[[0., 0., 0.],<br> [0., 0., 0.],<br> [0., 1., 0.]]</pre><p>By inspecting the model and understanding its inputs and outputs, we now know things that we are required to do in the Swift code:</p><ol><li>Convert the board state into a 2D array (3x3) where current player cells are 1.0, opponent cells are -1.0 and empty cells are 0.0 as input to the model.</li><li>Interpret the model output as 0.0 for a bad move and 1.0 for a best move.</li></ol><p>Let’s get started!</p><h4>Step 2: Integrate the model in your iOS project</h4><p>The UI of the app is a Tic Tac Toe board that enables the user to setup any board state and a button to switch the current player (“Next move”). The background of the empty cells in the board are shaded according the output of the model — dark grey is a higher value and a better move than a light grey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ThoiOa6cVjdJG4EusqnkgA.png" /></figure><p><strong>1.Add the model locally and on cloud. </strong>We already did this for a local only model in the previous example. In this example, let’s also add the model to the server — ready so that we can update our model in the future (without our users having to update the app). We can do that by placing the TensorFlow Lite model file in the Xcode project for local as well as upload your TensorFlow Lite model file into Firebase Console under the ML Kit Custom Models section to make it available on cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*n60KFgjFL8Yg8QCfunExnQ.png" /></figure><p><strong>2. Prepare an interpreter. </strong>As before, load the model by configure your model sources and create a ModelInterpreter object from one of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/816c808e70f3236ecb87f8fc3e7faaa2/href">https://medium.com/media/816c808e70f3236ecb87f8fc3e7faaa2/href</a></iframe><p>As you can see, the steps to configure a local model are the same. However there are some extra configuration steps for remote (on cloud) models. Firstly, create a CustomRemoteModel object by specifying the name of the model that you assigned when you published it via Firebase Console. Another part that we need before create a ModelInterpreter is starting a model download task by passing a CustomRemoteModel with the download conditions.</p><p>Then, we can create a ModelInterpreter from one of the models, local or remote by checking whether the remote model has been downloaded already before using it.</p><p><strong>3.Specify the model’s input and output. </strong>The Tic Tac Toe model has [3,3] as input and output shapes. Input is a current state of the board which is a 2D arrays that include -1 (opponent cell), 0 (empty cell), 1 (current player cell). The output is also 2D arrays which is the scores of all the moves as described in the inspect step above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29dff9c46e32524e3385d12d50725cd2/href">https://medium.com/media/29dff9c46e32524e3385d12d50725cd2/href</a></iframe><p><strong>4. Perform inference on input data. </strong>Here come the fun part! Every time the board state or the player changes in the user interface, we call the run function of the interpreter to get the best moves for the current player.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d5c5eda526e0938bf3eb7d76ff50603/href">https://medium.com/media/4d5c5eda526e0938bf3eb7d76ff50603/href</a></iframe><p>In the run function, there are quite a lot of checking to ensure that the input and output dimension are correct. If it is all good, then the output will be send back to show the scores in the view controller.</p><p>I hope these <a href="https://medium.com/@naluinui/firebase-ml-kit-custom-models-for-ios-developers-part-1-understanding-tensorflow-lite-123dfcfdce29">Part 1</a> and Part 2 together would help you to get started with custom models on Firebase ML Kit and will be able to add more complex models to your iOS apps in the future.</p><p>Firebase ML Kit is still in beta and therefore might change — keep an eye on the <a href="https://firebase.google.com/docs/ml-kit/ios/use-custom-models">official documentation for Custom Models on iOS</a> for the latest examples.</p><p>Get the full project code for these examples at <a href="https://github.com/naluinui/mlkit-custom-model-ios">github.com/naluinui</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44f1cd9f99c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebasethailand/firebase-ml-kit-custom-models-for-ios-developers-part-2-implementing-tic-tac-toe-44f1cd9f99c5">Firebase ML Kit Custom Models for iOS developers — Part 2: Implementing Tic Tac Toe</a> was originally published in <a href="https://medium.com/firebasethailand">Firebase Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase ML Kit Custom Models for iOS developers — Part 1: Understanding TensorFlow Lite]]></title>
            <link>https://medium.com/firebasethailand/firebase-ml-kit-custom-models-for-ios-developers-part-1-understanding-tensorflow-lite-123dfcfdce29?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/123dfcfdce29</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-kit]]></category>
            <category><![CDATA[firebase-ml-kit]]></category>
            <category><![CDATA[tensorflow-lite]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Sat, 04 Jan 2020 16:34:15 GMT</pubDate>
            <atom:updated>2020-01-07T10:54:38.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hum5ovHrkm7WUa62yaZwKQ.png" /></figure><h3>Firebase ML Kit Custom Models for iOS developers — Part 1: Understanding TensorFlow Lite</h3><p>First of all, I’d like to say that I am not an AI expert. I have zero knowledge about machine learning! But as a mobile developer, there is a good chance that your organisation will be using ML in their mobile apps in the future. I found myself in this situation and that brings me here to share what I have learnt so far.</p><p>Firebase has a product called <a href="https://firebase.google.com/products/ml-kit"><strong>ML Kit</strong></a> which can take some of the pain out of the machine learning on mobile apps (supports both iOS and Android). Firebase ML Kit has several built-in models that require only a few lines of code to do image classification, object detection, and OCR on-device and in the cloud.</p><p>However, the fun starts when you get given a specific custom model created by a data scientist in your organisation. They might also provide you some input and output examples and then you need to figure out the way to implement it into your mobile app. Luckily you can still use Firebase ML Kit, with a feature they call “Custom Models”. The main feature of ML Kit Custom Models is that any TensorFlow Lite model can be served to both your Android and iOS apps, include the model on device but also keep it updated automatically from the server.</p><p>I have seen some examples of the complicated custom models like an image classification, and so on which I found that it is quite difficult for me to get my head around it to start with. In this article and the next, I’m going to walk through the iOS implementation of 2 simple custom models that the data science geeks in the <a href="http://www.rfcx.org/">Rainforest Connection</a> team kindly created for me. I think having these models would have help me understand custom models better when I was getting started.</p><h3>The “Hello world” of custom models</h3><h4>Step 1: Inspect the model</h4><p>Before we start using Firebase ML Kit custom model, I found it is really helpful to understand how a model works first — especially its input and output.</p><p>I’m going to start off with the easiest model that I could think of. It is a model that takes 3 numbers (floats) as its input and it will output the sum of the numbers. It is certainly not a model that you need ML for, but it will help us see how the TensorFlow Lite model works.</p><p>Download the <a href="https://github.com/naluinui/mlkit-custom-model-ios/raw/master/mlkit-custom-model-ios/Resources/sum.tflite">sum.tflite</a> model.</p><p>If you open it in <a href="https://github.com/lutzroeder/netron">Netron</a> (a model visualiser) then you will see the inputs and outputs:</p><ul><li>Input type: float32[3] (a 1D array of length 3)</li><li>Output type: float32[1] (a 1D array of length 1)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUwyEiAic0iEviROMotFug.png" /><figcaption>The sum.tflite model visualised in Netron.</figcaption></figure><p>At its simplest, a TensorFlow Lite model is a function that takes inputs and produces outputs, where the input and output have fixed dimensions and lengths (known as the <em>shape</em>). Mostly you hear about image classification problems such as the input is a greyscale 200 by 200 pixel image (e.g. 2D array of floats with shape [200,200]) and the output is the probability it is a cat (e.g. 1D array of floats with shape [1]). In the sum model, the input is shape [3] and the output is shape [1] — our job as an iOS developer is to pass the data into the model and get the results following these shapes.</p><p>Before we implement the Swift code, if you are interested how the sum model was constructed in TensorFlow then you can <a href="https://colab.research.google.com/drive/1SX_IIbsyuLdFGYqQJ7J6uxeMkxfDD_OM">explore the python code in Colab</a>. It consists of the definition of the function and saving the function in tflite format, or you can see a short version of the code here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/886f1c758c37a7168fa01f7798e01bae/href">https://medium.com/media/886f1c758c37a7168fa01f7798e01bae/href</a></iframe><h4>Step 2: Integrate the model in your iOS project</h4><p>Next we create an iOS project and include the dependencies for Firebase custom models. (For Cocoapods, use pod &#39;Firebase/MLModelInterpreter&#39;) Then to keep our view controller clean, we put the interpreter logic in a separate class, so we will describe 2 files:</p><ul><li><em>SumViewController</em> has a button that generates 3 random numbers that are used as input to the model, and two labels to show the input and output.</li><li><em>SumInterpreter</em> class to handle loading and preforming the model.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*nwN_w4mCwG6_7xE2HkZRPA.png" /></figure><p><strong>1.Make the model available.</strong> You can either bundle your model with the app binary, or host it on the cloud via Firebase console, or both. By hosting a model on Firebase, you can update the model without releasing a new app version, and you can use Remote Config and A/B Testing to dynamically serve different models to different sets of users. By bundling your model within your app, you can ensure the ML features still work when Firebase-hosted model isn’t available (e.g. when offline). With this example, I will only bundle the model on device by placing sum.tflite model in the Xcode project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*tNN2b_qSKaHsb7Cjxzvjig.png" /><figcaption>Place a TensorFlow Lite model in the iOS project</figcaption></figure><p>2. <strong>Prepare an interpreter. </strong>First, we need to load the model by specify the locations of the model, on cloud, on device, or both. As our sum model only serves on device, so what we need to do is specify the filename of a TensorFlow Lite model inCustomLocalModel object. Then, create a ModelInterpreter object by simply pass the CustomLocalModel object in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cb2efa4f8d534dcf831765a34e07f6f/href">https://medium.com/media/4cb2efa4f8d534dcf831765a34e07f6f/href</a></iframe><p>3. <strong>Specify model’s input and output. </strong>As I mentioned earlier, this step is really important — try getting your input/output right! The model’s input and output use one or more multidimensional arrays which contain either byte, int, long, or float values. Specify your model’s input and output by using a ModelInputOutputOptions which required you to define the number and dimensions (shape) of the array your model uses. In the sum model, the input is shape [3] and the output is shape [1].</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df82443801373498a8b6d9a6f57b83eb/href">https://medium.com/media/df82443801373498a8b6d9a6f57b83eb/href</a></iframe><p>4. <strong>Perform inference on input data.</strong> Finally, to perform inference using the model, get your input data ready then pass it on to your model interpreter’s run method with the input/output options. For this example, I am just going to generate 3 numbers from ViewController, then pass them on to run method in the Interpreter class. Once we get the output, pass it back via the completion to show in ViewController.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ed1c4cc57c7e0d18f86321f9e4d59a3/href">https://medium.com/media/7ed1c4cc57c7e0d18f86321f9e4d59a3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7ff12b3ac3fe6e20549f1dc6c54e56c/href">https://medium.com/media/b7ff12b3ac3fe6e20549f1dc6c54e56c/href</a></iframe><p>This example is pretty easy, right? In <a href="https://medium.com/@naluinui/firebase-ml-kit-custom-models-for-ios-developers-part-2-implementing-tic-tac-toe-44f1cd9f99c5">Part 2</a> we are going to look at a more realistic example of playing Tic Tac Toe. Stay tuned!</p><p>Firebase ML Kit is still in beta and therefore might change — keep an eye on the <a href="https://firebase.google.com/docs/ml-kit/ios/use-custom-models">official documentation for Custom Models on iOS</a> for the latest examples.</p><p>Get the full project code for these examples at <a href="https://github.com/naluinui/mlkit-custom-model-ios">github.com/naluinui</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=123dfcfdce29" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebasethailand/firebase-ml-kit-custom-models-for-ios-developers-part-1-understanding-tensorflow-lite-123dfcfdce29">Firebase ML Kit Custom Models for iOS developers — Part 1: Understanding TensorFlow Lite</a> was originally published in <a href="https://medium.com/firebasethailand">Firebase Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ทำ Passwordless Authentication (Email link) ด้วย Firebase]]></title>
            <link>https://medium.com/firebasethailand/%E0%B8%97%E0%B8%B3-passwordless-authentication-email-link-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-firebase-47e554937da4?source=rss-2ec7fac6db8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/47e554937da4</guid>
            <category><![CDATA[email-links]]></category>
            <category><![CDATA[magic-link]]></category>
            <category><![CDATA[passwordless]]></category>
            <category><![CDATA[firebaseauthentication]]></category>
            <dc:creator><![CDATA[Nui Somjin]]></dc:creator>
            <pubDate>Mon, 31 Dec 2018 02:59:03 GMT</pubDate>
            <atom:updated>2019-05-27T12:18:41.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kf_IbXLJmi_AYGvPNBK_TQ.png" /></figure><p>เพราะการยืนยันตัวตน ไม่ได้มีแค่ password อีกต่อไป…</p><p>จริงๆ หลักของการยืนยันตัวตน เพียงแค่ต้องการรู้ว่าใช่คนๆนี้จริงไหม ซึ่งก็ทำได้หลากหลายวิธีด้วยกัน: ยืนยันด้วย <strong>สิ่งที่รู้ </strong>อย่าง<strong> </strong>password<strong> สิ่งที่มี</strong> อย่าง กุญแจ, smart card หรือ <strong>สิ่งที่เป็น </strong>อย่าง fingerprint และ biometric</p><p>วิธีการสุดเบสิคในการยืนยันตัวตนทั้งบนแอปมือถือและเว็บไซต์ทุกยุคทุกสมัย ก็คงหนีไม่พ้น <strong>password</strong> ซึ่ง password เป็นการยืนยันตัวตนด้วยสิ่งที่รู้<em> (ที่คนอื่นก็ห้ามรู้!) </em>ปัญหาของ password ก็คือ ต้องง่ายพอที่จะจำได้ แต่ต้องไม่ง่ายไปจนคนอื่นเดาออก เหตุผลที่คนไม่อยากสร้าง password เพิ่ม เพราะต้องใช้พื้นที่สมองในการจดจำเพิ่ม คนส่วนใหญ่จึงรู้สึกสบายใจที่จะยืนยันตัวตนด้วยสิ่งที่มีอยู่แล้วมากกว่า ซึ่งเป็นไอเดียของ Passwordless Authentication ที่ใช้สิ่งที่มีอยู่แล้วอย่าง email account หรือเบอร์โทรศัพท์ในการยืนยันตัวตนแทน password</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oj8PCaUEr6_-Pt5TM0mtxg.jpeg" /><figcaption>Slack ใช้ email ในการ Authentication</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NZzoCyj4-6U5V2Fh6RttoQ.png" /><figcaption>Medium เอง ก็ยังมีทางเลือกให้ใช้ Email ในการ Authentication</figcaption></figure><p>ซึ่ง 2–3 ปีมานี้ ก็เริ่มมีการใช้ Passwordless Authentication กันมากขึ้น แต่อาจจะยังไม่แพร่หลายมากนัก ด้วยข้อจำกัดที่ต้องพัฒนาทั้ง backend และ frontend ซึ่งหลายทีมก็อาจจะรู้สึกว่ายังไม่อยากจะเสียเวลาและ effort ไปกับตรงนั้นมากนัก แต่ตอนนี้ขอบอกเลยว่าง่ายกว่าเดิมเยอะ เพราะเริ่มมีหลายๆ service ที่ทำให้การพัฒนาระบบ Passwordless Authentication ง่ายขึ้นเยอะมาก ไม่ว่าจะเป็น Auth0 หรือ Firebase</p><h3>Passwordless Authentication with Firebase</h3><p>หลักการก็เหมือนที่ Slack และ Medium ใช้เลย คือ ผู้ใช้กรอกแค่ email จากนั้นจะมี link ที่คลิกแล้วสามารถเข้าสู่ระบบได้เลยส่งไปให้ ซึ่ง<strong>ไม่ได้มีข้อดีแค่ user ไม่ต้องจำ password เพิ่ม</strong> แต่วิธีการนี้ยัง…</p><ul><li>ช่วยลดความเสี่ยงในการใช้ password ซ้ำกันหลายๆ account ของ user</li><li>ช่วย verify ว่า user เป็นเจ้าของ email จริงๆ</li><li>ใช้แค่ email account ไม่จำเป็นต้องมีเบอร์โทรศัพท์ หรือบัญชี social media</li><li>user ปัจจุบันที่อาจจะเคยสมัครสมาชิกไว้ แต่ลืม password ไปแล้ว สามารถเข้าสู่ระบบได้ โดยไม่จำเป็นต้อง reset password</li></ul><p>ซึ่งวันนี้เราจะมาลองทำ Passwordless Authentication แบบง่ายๆ ด้วย Firebase ตาม flow ด้านล่างนี้</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TK3VfDGSjC2q81vXLvno6Q.png" /><figcaption>กรอก email เพื่อรับ link &gt; กด link จาก email เพื่อเข้าสู่ระบบ</figcaption></figure><p><strong>1. เปิดใช้งาน Passwordless sign-in</strong> โดยเข้าไปที่เมนู Authentication ใน Firebase console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*jM7yYKyE4W9YtI646YqTJQ.png" /></figure><p><strong>2. เปิดใช้งาน Dynamic links และ Setup แอปเพื่อให้สามารถรับ dynamic links ได้ </strong>(กรณีที่ยังไม่เคยใช้งาน Dynamic links มาก่อน) โดยเข้าไปที่ Firebase console และทำตามขั้นตอน 2–3 steps ส่วนการ setup ในแอปขอสรุปเป็นขั้นตอนสั้นๆ ดังนี้</p><ul><li><strong>ติดตั้ง Dynamic links</strong> โดยทำการ install pod ‘Firebase/DynamicLinks’ เข้ามาในโปรเจค</li><li><strong>ตั้งค่า URL Types</strong> ใน <strong>Info</strong> tab ของโปรเจค โดยใช้ $(PRODUCT_BUNDLE_IDENTIFIER) เป็น URL Scheme</li><li><strong>ตั้งค่า</strong> <strong>Associated Domains</strong> ใน <strong>Capabilities</strong> tab ของโปรเจค — enable Associated Domains แล้ว add domain ที่เพิ่งสร้างมาจากข้อ 2 ลงไป ตาม format ดังนี้ applinks:your_subdomain.page.link</li><li><strong>ตั้งค่า iOS bundle ID, App Store ID และ Apple Developer Team ID</strong> ที่ Project Setting ใน Firebase Console</li></ul><p><strong>3. ติดตั้ง Firebase Authentication ในแอป </strong>(กรณีที่ยังไม่เคยใช้งาน Authentication ของ Firebase มาก่อน) โดยทำการ install pod ‘Firebase/Auth’ เข้ามาในโปรเจค</p><p><strong>4. Implement หน้าสำหรับขอ</strong> <strong>Passwordless sign-in link </strong>— จริงๆตามใจเลยแหละว่าอยากได้หน้าตา หรือ flow ของแอปแบบไหน ตามตัวอย่าง มีแค่ TextField ไว้ให้ user กรอก email และปุ่มเพื่อกดขอรับ link</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*vYGue_iV68G5CWCWF1W3bA.png" /><figcaption>UI สำหรับขอ Passwordless authentication link</figcaption></figure><p><strong>5. ส่ง Passwordless sign-in link ให้ user </strong>โดยการเรียก function sendSignInLinkToEmail:actionCodeSettings:completion: จะเห็นว่า function นี้รับ parameters 2 ตัวด้วยกัน นั่นก็คือ <strong>email </strong>และ<strong> ActionCodeSettings </strong>ซึ่งแน่นอน <strong>email</strong> เราได้จาก user อยู่ละ แล้ว <strong>ActionCodeSettings </strong>ล่ะ มาจากไหนกัน?</p><p><strong>ActionCodeSettings </strong>เป็น object ที่เราสามารถ set คุณสมบัติต่างๆให้กับ link ที่จะถูกส่งให้ user โดยค่าที่ต้อง set มีดังนี้</p><ul><li><strong>iOSBundleID และ AndroidPackageName </strong>แอปที่ต้องการจะเปิด ถ้า user กด link นั้นจาก email บนมือถือ</li><li><strong>handleCodeInApp </strong>อันนี้ต้อง set เป็น <strong>true </strong>เสมอ เพราะสุดท้ายแล้วตอนจบของ flow Passwordless sign-in นี้คือ user เค้าต้องการเข้าสู่ระบบในแอปไงล่ะ คนดี</li><li><strong>url</strong> url นี้จะถูกใช้ในกรณีที่ user กด link จาก email ในช่องทางอื่นๆ เช่น กดจากในคอม หรือกดในมือถือเครื่องอื่นที่อาจจะไม่ได้ลงแอปไว้… โดยเราอาจจะตั้ง url ตรงนี้เป็น static page โง่ๆที่บอกว่า หึ่ย แก แกต้องกด link จาก email ในเครื่องที่แกติดตั้งแอปไว้เท่านั้นนะเว้ย …หรือบางคนอาจมีท่ายากกว่านั้น แบบว่า ถ้า user ไปกด link ในเครื่องที่ยังไม่มีแอป อยากพา user ไปหน้า download แอปเลย พอ download เสร็จกดเข้ามา ก็อยากจะ sign-in ให้ user เลย แบบนี้ก็อาจต้องตั้ง url ตรงนี้เป็น dynamic link ที่แนบ email เป็น query string ไปด้วย เพื่อ handle ในท่าที่ยากๆแบบนั้นได้ ซึ่งเอาจริงคือ ก็แล้วแต่เราแหละว่าต้องการให้ flow มันออกมาเป็นรูปแบบไหน แต่สิ่งที่สำคัญคือ <strong>โดเมนของ url นี้จะต้องอยู่ใน Authorised domains</strong> ซึ่งเราสามารถเข้าไป set ได้ที่เมนู Authentication &gt; Sign-in Method ใน Firebase Console</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/705f14c9f09a1b485455d63803b5ceb9/href">https://medium.com/media/705f14c9f09a1b485455d63803b5ceb9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*L1ckN6FufDb8sf5gmka6aA.png" /><figcaption>อย่าลืมเอา domain ของ url ที่ใช้ มาเพิ่มใน Authorised domains</figcaption></figure><p>เมื่อสร้าง <strong>ActionCodeSettings </strong>และมี <strong>email</strong> พร้อมแล้ว ก็ได้เวลาส่ง link ให้ user โดยถ้าส่งเรียบร้อยแล้ว เราจะแอบเก็บ email ไว้ในแอปด้วย เพื่อเอาไว้ sign-in ให้ user ในขั้นตอนถัดไป</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18fc67d1dee65f2e66cdc2bf2bff7050/href">https://medium.com/media/18fc67d1dee65f2e66cdc2bf2bff7050/href</a></iframe><p>ลองไปเช็ค email จะได้ email ลักษณะนี้ ซึ่งถ้าลองแกะ link ดู มันก็คือ dynamic link ที่มี query string เกี่ยวกับการ sign in เพิ่มเข้ามา ซึ่ง Firebase generate มาให้จาก ActionCodeSettings ที่เรากำหนดไปข้างต้นนั่นแหละ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Zg_kJvE48YNkLHMkVKH9xA.png" /><figcaption>Email ที่ได้รับ</figcaption></figure><p><strong>6. รับมือตอน user กด link จาก email — </strong>อย่างที่บอกว่า link ที่ได้ ก็เป็น dynamic links ทั่วไปนั่นแหละ ซึ่งแปลว่าเราก็ต้อง handle ในแอปเหมือนกับ dynamic links รูปแบบอื่นๆ</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88f4204359744ef0054db0865a66849a/href">https://medium.com/media/88f4204359744ef0054db0865a66849a/href</a></iframe><p>ด้วยการ verify ก่อนว่า link นี้ เป็น sign-in link มั้ย ถ้าใช่ ก็จะทำการ sign-in เข้าสู่ระบบให้ user ด้วย <strong>link</strong> (ที่เพิ่งได้มา) และ <strong>email</strong> (ที่แอบ save เอาไว้ในแอปตั้งแต่ขั้นตอนก่อนหน้านี้) ได้เลย</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa62c36c1d0bfdef6dfc252c7ed88010/href">https://medium.com/media/fa62c36c1d0bfdef6dfc252c7ed88010/href</a></iframe><p>การ sign-in ก็แค่เรียก signInWithEmail:link:completion:ซึ่งถ้าไม่มีอะไรผิดพลาด เราก็จะได้ข้อมูล user กลับมา และถือว่าการ sign-in เสร็จสมบูรณ์แล้ว ฮูเร! 🥳</p><p><strong>ข้อจำกัด <br></strong>ตอนนี้ใน Firebase ยัง customise email ไม่ได้<strong> </strong>ก็คือ email ที่ user จะได้รับ หน้าตาจะโล้นๆ เหมือนกับภาพที่แนบไว้ด้านบน แต่คาดว่าอีกไม่นานคงทำได้เหมือนกับเจ้าอื่นๆ</p><p>สุดท้ายนี้ ก็หวังว่าบทความนี้จะเป็นประโยชน์กับทุกๆคนนะคะ ไม่ว่าจะเป็นคนที่ยังลังเลอยู่ว่าจะทำดีมั้ย หรือคนที่อยากทำแต่ไม่รู้จะเริ่มยังไง</p><p>จริงๆ อยากบอกว่า ทำเลยค่ะ มีคนรอใช้อยู่ 🙋‍♀️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47e554937da4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/firebasethailand/%E0%B8%97%E0%B8%B3-passwordless-authentication-email-link-%E0%B8%94%E0%B9%89%E0%B8%A7%E0%B8%A2-firebase-47e554937da4">ทำ Passwordless Authentication (Email link) ด้วย Firebase</a> was originally published in <a href="https://medium.com/firebasethailand">Firebase Thailand</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>