Service Component Creation for REST API

Learn how to create a service component in a REST API with local storage.

Create the service component

A directory called services is created to store the service components, then inside that directory, the service component is created in the file called services.go. After that, some functionalities are added based on the project’s specifications. Inside services.go, a new variable called storage is created to store the item’s data.

package services

import (
	"go-simple-inventory/models"
)

var storage []models.Item = []models.Item{}

Get all items

Inside the services.go file, a function is created to get all items from the storage.

// GetAllItems returns all items data
func GetAllItems() []models.Item {
	return storage
}

Based on the code above, the GetAllItems() function returns the storage that contains all item data.

Get item by ID

Inside the services.go file, a function is created to get the item’s data by ID.

// GetItemByID returns get item's data by ID
func GetItemByID(id string) (models.Item, error) {
    // iterate through all items
	for _, item := range storage {
        // if current item's ID equals ID in the parameter
		if item.ID == id {
            // return the item's data
			return item, nil
		}
	}

    // return error if item not found
	return models.Item{}, errors.New("item not found")
}

Based on the code above, the item is searched using a for loop. If the item is found, then the item is returned. Otherwise, the error is returned.

Create a new item

Inside the services.go file, a function is created to create a new item inside storage.

// CreateItem returns created item in the storage
func CreateItem(itemRequest models.ItemRequest) models.Item {
    // create a new item
	var newItem models.Item = models.Item{
		ID:        uuid.New().String(),
		Name:      itemRequest.Name,
		Price:     itemRequest.Price,
		Quantity:  itemRequest.Quantity,
		CreatedAt: time.Now(),
	}

    // store the created item into storage
	storage = append(storage, newItem)

    // return the item that already created
	return newItem
}

In the code above, the item’s data is created, then the item is stored inside storage with the append() function. This function returns the item that was already created.

Update item by ID

Inside the services.go file, a function is created to update the item’s data by ID.

// UpdateItem returns updated item
func UpdateItem(itemRequest models.ItemRequest, id string) (models.Item, error) {
    // iterate through all items
	for index, item := range storage {
        // if item is found
		if item.ID == id {
            // update the item's data
			item.Name = itemRequest.Name
			item.Price = itemRequest.Price
			item.Quantity = itemRequest.Quantity
			item.UpdatedAt = time.Now()

			storage[index] = item

            // return the updated item
			return item, nil
		}
	}

    // return error if update is failed
	return models.Item{}, errors.New("item update failed, item not found")
}

In the code above, the item that will be updated is searched using a for loop. If the item is found, the item’s data is updated, then the updated item is returned. Otherwise, the error is returned.

Delete an item by ID

Inside the services.go file, a function is created to delete items by ID.

// DeleteItem returns deletion result
func DeleteItem(id string) bool {
    // create a new slice for storing items data
    // after deletion
	var newItems []models.Item = []models.Item{}

    // iterate through all items
	for _, item := range storage {
        // if current item's ID is not equal ID in parameter
        // insert the item into "newItems" slice
		if item.ID != id {
			newItems = append(newItems, item)
		}
	}

    // assign the "newItems" into storage
	storage = newItems

	return true
}

As seen in the code above, the delete mechanism is implemented by filtering the item’s data that is not equal to the id from the parameter, then true is returned.

The complete code for services.go can be seen in the application below:

Get hands-on with 1400+ tech skills courses.